資料庫約束六大約束語句

2021-10-17 07:55:25 字數 1857 閱讀 6518

#新增 not null

alter table user modify name varchar(20) not null

#刪除 not null

alter table user modify name varchar(20)

#新增 unique

alter table user add unique(name)

#刪除 unique

alter table user drop index name

#新增主鍵

alter table user modify id int primary key

#刪除主鍵

alter table user drop primary key

#id自增長

alter table user modify id int auto_increment

#刪除自增

alter table user modify id int

#建立外來鍵

constraint 外來鍵名稱(自起) foreign key (外來鍵列) references 主表名(主表列)

#刪除外來鍵

alter table 表名 drop foreign key 外來鍵名稱

#新增外來鍵

alter table 表名 constraint 外來鍵名稱(自起) foreign key (外來鍵列) references 主表名(主表列)

#級聯更新/刪除

on update/delete cascade

①check約束用於限制列中的值的範圍

②如果對個單個列做check約束,那麼該列只可以輸入特定數值

③如果乙個表定義check約束,那麼此約束會在特定的列對值進行限制

④語法:

1.studentid int not null check (studentid>0)          限制studentid輸入的值要大於0  (sql server  oracle)

2.studentid int not null, check (studentid>0) 限制studentid輸入的值要大於0 (mysql)

3.*** varchar(2) not null check(***='男' or ***='女') 限制***的性別只能是男或者女

4.alter table table_name add check(列名》0) 向已有的列加入check約束

5.alter table table_name drop constraint check約束名 刪除約束 約束名可以用 sp_help table_name檢視

①default約束用於向列中插入預設值

②如果沒有規定其他的值,那麼會將預設值新增到所有的新記錄中

③語法:

1.name varchar(10) default '張三'                        name預設插入張三的名字

2.systime date default gatedate() 插入時間的預設值 getetime()函式為時間的預設值

3.alter table table_name add 列名 set default '數值' 向已有列名中插入預設值

4.alter table table_name drop constraint 約束名 刪除預設約束

SQL六大約束

該字段的值不能為空。如果插入資料時,該欄位沒有賦值,則為預設值。該欄位不能重複,且不能為空。比如學號。乙個表中只能有乙個主鍵約束。通過表級約束對兩個字段設定聯合主鍵 該字段值不能重複,可以為空,但只能有乙個null值。比如座位號。乙個表中可以有多個唯一約束。用於檢查字段值是否正確。比如檢查年齡是否規...

Mysql表操作及六大約束

動作 sql建立表 create table表名 欄位名 欄位名型別 長度 更新表名 rename table 舊表名 to 新錶名 更新欄位名 alter table 表名 change 舊欄位名 新欄位名 新欄位名型別 長度 更新字段型別 null 預設值 alter table 表名 modi...

資料庫五大約束

所謂約束,其實就是一種保障,比如乙個屬性新增了主鍵約束,那麼就強制保障了它的唯一性和非空性,請帶著這樣正確的理解去閱讀後文。資料庫有五大約束,分別是 主鍵約束的要求是 唯一,非空 因此主鍵不需要 也不能再設定唯一約束了。另外,主鍵可以設定自動增長,而且,主鍵不一定是自動增長的,但自動增長的一定是主鍵...