sql中表達完整性約束

2022-09-02 23:12:25 字數 1325 閱讀 3857

sql約束性分為實體完整性,參照完整性,使用者定義完整性,刪除約束

實體完整性

1.建表時定義主鍵

create table 表名

(sno int identity(1,1),

sname nvarchar(20),

--設定主鍵

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     --級聯刪除

on update cascade    --級聯更新

-- 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_表名_列

—實體完整性:又稱行完整性,要求在表中不能存在完全相同的行,而且每行都要具有乙個非空且又不重複的主鍵值。

—使用者自定義完整性:指針對某一具體關聯式資料庫的約束條件,它反映某一具體應用所涉及的資料必須滿足的語義要求。

—參照完整性:又稱引用完整性,指表間的規則,作用於有關聯的兩個或兩個以上的表,通過使用主鍵和外來鍵(或唯一鍵)之間的關係,使表中的鍵值在相關表中保持一致

SQL完整性約束

完整性約束保證授權使用者對資料庫所做的修改不會破壞資料的一致性。not null宣告禁止在該屬性上插入空值。任何可能導致向乙個宣告為not null的屬性插入空值的資料都會產生錯誤診斷資訊。unique aj 1 aj 2 aj m unique宣告指出aj 1 aj 2 aj m 形成了乙個候選碼...

SQL完整性約束

1.資料定義語句 ddl create alter drop truncate 表結構 2.資料操縱語句 dml insert delete update select 3.資料控制語句 dcl 授權 grant 收回許可權 revoke 4.失誤控制語句 tcl 開啟事務 begin transa...

完整性約束

create table student tb id int notnull 非空約束 資料不允許為空 name varchar 255 null 顯式指定允許為空 新增非空約束 alter table 表名 modify column 屬性名 屬性型別 not null alter table s...