必須會的SQL語句(八) 數(shù)據(jù)庫的完整性約束
實體完整性
1.建表時定義主鍵
Create table 表名
(
Sno int identity(1,1),
Sname nvarchar(20),
--設(shè)置主鍵
Primary key (Sno)
)
2.添加主鍵
alter table 表名
add constraint PK_表名_Sno
primary key(id)
參照完整性1.建表時定義外鍵
create table 表名
(
sno int identity(1,1) primary key,
cno int not null,
foreign key(cno) References
表名2(Cno)
on Delete cascade --級聯(lián)刪除
on update cascade --級聯(lián)更新
-- on delete on action 刪除管制
)
2.添加外鍵
alter table 表名
add constraint FK_表名_表名2
Foreign key(cid) references 表名2(cid)
用戶定義完整性1.非空約束
alter table 表名
alter column name varchar(20) not null
2.唯一約束
alter table 表名
add constraint UQ_表名_列名 unique(列)
3.檢查約束
alter table 表名
add constraint CK_表名_列名 check(age>5)
4.默認約束
alter table 表名
add constraint DF_表名_列名 default('男')
for gender
刪除約束 --刪除約束
alter table 表名 drop constraint DF_表名_列
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信