資料庫的約束

2021-08-18 06:40:23 字數 1373 閱讀 6359

--新增相關約束

--建立主鍵約束

if exists (select * from sysobjects where name = 'pk_studentid')

alter table students drop constraint pk_studentid

alter table students add constraint pk_studentid primary key(studentid)

--建立唯一約束(unique key)

if exists (select * from sysobjects where name = 'uq_studentidno')

alter table students drop constraint uq_studentidno

alter table students add constraint uq_studentidno unique (studentidno)

--檢查約束和預設約束

--建立預設約束

if exists (select * from sysobjects where name = 'df_studentaddress')

alter table students drop constraint df_studentaddress

alter table students add constraint df_studentaddress default ('位址不詳') for studentaddress

--建立檢查約束

if exists (select * from sysobjects where name = 'ck_age')

alter table students drop constraint ck_age

alter table students add constraint ck_age check (age between 18 and 25)

--建立外來鍵約束

if exists (select * from sysobjects where name = 'fk_classid')

alter table students drop constraint fk_classid

alter table students add constraint fk_classid foreign key(classid) references studentclass(classid)

外來鍵使用:

要求資料型別、資料長度必須與對應的主鍵表字段完全一致

新增資料時,要首先新增主鍵表,再新增外來鍵表

刪除資料時,要首先刪除外檢表資料,再刪除主鍵表資料

完整資料庫建立步驟:

建庫->建表->主鍵約束->域完整性約束->外來鍵約束

資料庫的約束

資料庫的約束條件 新增約束 alter table 表名 add constraint 約束名 約束型別 具體說明 學生編號,主鍵約束 add constraint pk stuno primary key stuno 學生身份證號,唯一約束 add constraint uq stuid uniq...

資料庫的約束

什麼是資料庫的約束?我認為資料庫的約束就是限制資料庫表中的約束條件。約束一共分為5種型別,分別為 sql server中有五種約束型別,分別是check約束 default約束 primary key約束 foreign key約束和unique約束。用於限制輸入一列或者多列的值的範圍,通過邏輯表示...

資料庫的約束

概念 對錶中的資料進行限定,保證資料的正確性 有效性和完整性 分類1 主鍵約束 primary key 2 非空約束 not null 3 唯一約束 unique 4 外來鍵約束 foreign key1 建立表時新增約束create table stu1 id int name varchar 5...