?一韭脊、一致性
一致性包括not null、unique塞帐、check
a)Not null
name varchar(20) not null
b)Unique
如果A1, A2...等構(gòu)成了候選鍵拦赠,可以用unique(A1, A2...)來保證其唯一性,但這些字段仍然可為空葵姥,而為空值與任何值都不相等荷鼠。
c)Check
限制semester的值:
check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)
d)Referential Integrity參照完整性
如果course.dept_name作為外鍵引用department表,為了保證course.dept_name的取值都存在于department.dept_name榔幸,添加參照完整性約束為:
e)foreign key (dept name) references department
二颊咬、數(shù)據(jù)類型和Schemas
a)Date和time
SQL標(biāo)準(zhǔn)規(guī)定的time相關(guān)類型有:
date ’2001-04-25’
time ’09:30:00’
timestamp ’2001-04-25 10:29:01.45’
字符串形式的日期可以使用cast e as t的方式來轉(zhuǎn)換务甥;也可以使用extract year/month/day/hour/minute/second from d的方式來單獨提取年月日等數(shù)據(jù);
還有current_day, current_timestamp(包含時區(qū)), localtimestamp(不包含時區(qū)的本地時間)喳篇;
interval類型表示時間的差
b)Default value
create table student
(ID varchar (5),
name varchar (20) not null,
dept name varchar (20),
tot_cred numeric (3,0) default 0,
primary key (ID));
這里設(shè)置了tot_cred的默認(rèn)值為0
c)創(chuàng)建索引
create index studentID index on student(ID)表示創(chuàng)建了名為studentID的索引敞临,有的數(shù)據(jù)庫產(chǎn)品又進(jìn)一步區(qū)分了聚集索引(clustered)與非聚集索引(nonclustered)
d)大對象類型Large-Object Type
如果要存儲聲音、圖像等數(shù)據(jù)麸澜,數(shù)據(jù)量可能為KB甚至MB, GB級別挺尿,為此SQL提供了兩種大對象類型 clob(character large object)和blob(binary...)。不同數(shù)據(jù)庫的具體實現(xiàn)會有區(qū)別炊邦,而且實際使用中不推薦使用這些類型编矾,而往往將數(shù)據(jù)保存在文件系統(tǒng),并在數(shù)據(jù)庫保存其存放位置馁害。
e)用戶自定義類型
允許基于現(xiàn)有的類型來自定義數(shù)據(jù)類型窄俏,比如:
create type Dollars as numeric(12,2);
create type Pounds as numeric(12,2);
自定義類型Dollars和Pounds雖然都是numeric(12,2)類型,但在業(yè)務(wù)上被認(rèn)為是不同的數(shù)據(jù)類型碘菜。
還有一種定義方式為:
create domain DDollars as numeric(12,2) not null;
type和domain的細(xì)微的區(qū)別在于domain可以同時添加約束如not null,凹蜈;而且domain也不是完全的強(qiáng)類型,只要值是兼容的忍啸,就可以賦值給domain定義的類型仰坦,而type卻不行。
e)Create table的擴(kuò)展
create table temp instructor like instructor;創(chuàng)建了一個與sinstructor有相同結(jié)構(gòu)的表
在編寫SQL時计雌,有時會創(chuàng)建臨時表并存入數(shù)據(jù)悄晃,這時可以用簡化寫法:
create table t1 as
(select *
from instructor
where dept name= ’Music’)
with data;
t1表結(jié)構(gòu)與查詢結(jié)果集相同,如果去掉with data凿滤,則只創(chuàng)建schema而不插入數(shù)據(jù)妈橄。
三、授權(quán)
權(quán)限控制可以針對用戶或角色進(jìn)行數(shù)據(jù)操縱翁脆、schema更新等的控制眷蚓。
a)分配、撤銷授權(quán)
分配權(quán)限的語法為:
grant
on
to ;
privilege list包括select, insert, update, delete
對于update鹃祖,可以設(shè)定允許更新某些屬性:
grant update (budget) on department to Amit, Satoshi;
類似地溪椎,撤銷授權(quán)語法為:
revoke
on
to ;
b)角色
基于角色的權(quán)限控制不是SQL的專利,很多共享型應(yīng)用都采用這種授權(quán)方式恬口。
create role instructor;
grant select on takes to instructor;
grant dean to Amit;
前面的語句創(chuàng)建了角色instructor校读,為期分配select from takes權(quán)限,然后將Amit歸入instructor角色祖能。在Amit執(zhí)行查詢前歉秫,SQL根據(jù)它所屬角色具有的權(quán)限來做控制。
c)關(guān)于schema的授權(quán)
因為外鍵會影響后續(xù)的更新养铸、刪除等操作雁芙,所以有必要為外鍵的創(chuàng)建做權(quán)限控制:
grant references (dept name) on department to Mariano;
學(xué)習(xí)資料:Database System Concepts, by Abraham Silberschatz, Henry F.Korth, S.Sudarshan