SQL 表的完整性

2022-09-15 10:33:19 字數 1015 閱讀 4789

建立:主外來鍵,約束。(刪除主表的時候,同時刪除子表;更新主表的時候更新子表)

create table 表名

sno int identity(1,1),

sname nvarchar(20),

--設定主鍵

primary key (sno)

新增主鍵

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  刪除管制

新增外來鍵

alter table 表名

add constraint fk_表名_表名2

foreign key(cid) references 表名2(cid)

使用者定義完整性1.非空約束

alter table 表名

alter column name varchar(20) not null

alter table 表名

add constraint uq_表名_列名 unique(列)

alter table 表名

add constraint ck_表名_列名 check(age>5)

alter table 表名

add constraint df_表名_列名 default('男')

for gender

alter table 表名 drop constraint df_表名_列

SQL 表和資料完整性

我們在設計資料庫的時候,研究需要建立幾張表。每張表要考慮如下問題 表的名稱 表中每一列的名稱 資料型別及長度 表中的列是否為空值 唯一 是否有預設值 約束 哪些是主鍵 外來鍵 例子 進入當前資料庫 use xscj go 建立表 語句 每一列的名稱 資料型別 特殊要求 create table st...

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...