Sql server--約束

1 缺省約束

    指當向數據庫中的表插⼊入數據時,若是⽤用戶沒有 明確給出某列的值,SQL SERVER⾃自動爲該列 輸⼊入默認值 sql

alert table 表名
數據庫

add constraint 缺省約束名spa

default 缺省值 for 列名rest

alert table worker
add constraint default_sex
default 1 for sex
go


2 檢查約束

    限制插入列中的值的範圍,主要⽤用於實現域完整性。它是當對數據庫中的表執行插入或更新操做時,檢查新⾏行中的列值必須滿⾜的約束條件 code

alert table 表名
table

add constraint 檢查約束名class

check (範圍表達式)im

alert table restock
add constraint ck_besNum
check(res_number >= 2)


3 主鍵約束

    ⽤來保證某一列或一組中的數據相對於表中的每一⾏行都是唯一的,這些列就是該表的主鍵,不容許在建立主鍵約束的列上有空值。 數據

alert table 表名tab

add constraint 主鍵約束名

primary key (clustered/nonclustered) (主鍵所在列名)

alert table users
add constraint pk_uname
primary key (username)


4 惟一約束

    限制表中指定列上全部非空值必須唯一,即表中任意兩行在指定列上都不容許有相同的值,與 主鍵不一樣的是,在Unique字段中容許出現NULL值,但爲了保持唯一性,最多隻能出現一次NULL值 

alert table 表名

add constraint 惟一性約束名

unique (clustered/nonclustered) (惟一性約束所在列名)

alert table users
add constraint uq_uname
unique (username)


5 外鍵約束

 要求正被插入或更新的列(外鍵)的新值,必須在被參照表(主表)的相應列(主鍵)中已經存在。 

alert table 表名

add constraint 外鍵約束名

foreign key (從表中外鍵所在的列名)

references 主表名(主表中主鍵的列名)

alert table sell
add constraint fk_sellId
foreign key(ware_id)
reference ware(ware_id)
go


刪除約束

alert table 表名

drop constraint 約束名

相關文章
相關標籤/搜索