資料庫中的五種約束

2021-08-20 13:48:41 字數 1296 閱讀 2592

資料庫中的五種約束

五大約束

1.—-主鍵約束(primay key coustraint) 唯一性,非空性

2.—-唯一約束 (unique counstraint)唯一性,可以空,但只能有乙個

3.—-檢查約束 (check counstraint) 對該列資料的範圍、格式的限制(如:年齡、性別等)

4.—-預設約束 (default counstraint) 該資料的預設值

5.—-外來鍵約束 (foreign key counstraint) 需要建立兩表間的關係並引用主表的列

五大約束的語法示例

1.—-新增主鍵約束(將stuno作為主鍵)

alter table stuinfo

add constraint pk_stuno primary key (stuno)

2.—-新增唯一約束(身份證號唯一,因為每個人的都不一樣)

alter table stuinfo

add constraint uq_stuid unique(stuid)

3.—-新增預設約束(如果位址不填 預設為「位址不詳」)

alter table stuinfo

add constraint df_stuaddress default (『位址不詳』) for stuaddress

4.—-新增檢查約束 (對年齡加以限定 15-40歲之間)

alter table stuinfo

add constraint ck_stuage check (stuage between 15 and 40)

alter table stuinfo

add constraint ck_stu*** check (stu***=』男』 or stu***=』女′)

5.—-新增外來鍵約束 (主表stuinfo和從表stumarks建立關係,關聯欄位stuno)

alter table stuinfo

add constraint fk_stuno foreign key(stuno)references stuinfo(stuno)

約束(constraint)是microsoft sql server 提供的自動保持資料庫完整性的一種方法,定義了可輸入表或表的單個列中的資料的限制條件(有關資料完整性的介紹請參見第9 章)。在sql server 中有5 種約束:主關鍵字約束(primary key constraint)、外關鍵字約束(foreign key constraint)、惟一性約束(unique constraint)、檢查約束(check constraint)和預設約束(default constraint)。

資料庫的五種約束

約束 1 非空約束not null 新增或修改記錄時該列的值不允許為空 2 check約束check sal 0 新增或修改記錄時該列的值需要滿足check設定的條件 3 主鍵約束primary key 新增或修改記錄時該列的值不能與其他記錄的該列值重複 4 唯一鍵約束unique 新增或修改記錄時...

資料庫五種約束型別的建表

五大約束型別 主鍵約束 外來鍵約束 唯一約束 非空約束 預設約束 1.主鍵約束 先來個普通表 create table tb2 username varchar 20 not null,age tinyint 3 unsigned default null 主鍵約束 建立自增序列,使用auto in...

資料庫技術五(約束)

目錄 約束 對錶中的資料進行限定,保證資料的正確性 有效性和完整性。約束的分類 主鍵約束 非空約束 唯一約束 外來鍵約束 非空約束 not null,值不能為null 1.建立表時新增約束 create table stu1 id int not null,name varchar 20 2.建立表...