sql server 常見約束



1.not null 非空約束
①強制列不接受空值
②例:創建表時,name varchar(6) not null,

 

 

2.unique 唯一性約束
①約束唯一標識數據庫表中的每條記錄
②unique和primary key都為數據提供了唯一性約束
③primary key 擁有自動定義的Unique約束
④注意:每個表中只能有一個primary key約束,但是可以有多個Unique約束
⑤語法:
1.name int unique
2.unique(column_name)
3.CONSTRAINT uc_PersonID UNIQUE (Id_P,LastName) 添加多個約束
4.alter table table_name add unique(column_name) 增加表中的約束
5.ALTER TABLE table_name DROP CONSTRAINT 主鍵名 刪除約束

 

 

 

3.primary key約束
①約束唯一標識數據庫表中的每條記錄
②主鍵必須包含唯一的值
③主鍵列不能為空
④每個表都應該有個主鍵,但只能有一個主鍵
⑤語法:
1.StudentID int not null primary key 創建學生編號為主鍵
2.primary key(Students) 創建學生編號為主鍵
3.primary key(StudentID,Email) 創建學生ID和Email為聯合主鍵
⑥為已存在的列創建主鍵
1.alter table table_name add primary key(column_name)
⑦刪除主鍵約束
1.alter table table_name drop primary key
⑧刪除主鍵約束
1.alter table table_name drop constraint 主鍵約束名 主鍵約束名可以使用sp_help查詢

 

 

 

 

4.foreign key約束
①一個表中的foreign key 指向另一個表的primary key
②foreign key約束用於預防破壞表之間連接的動作
③foreign key約束也能防止非法數據插入外鍵列,因為它必須是指向的那個表的值之一
④語法:
1.foreign key (column_name) references 主表名(主鍵列名) 創建column_name為主表名的外鍵
2.column_name int foreign key references 主表名(主鍵列名) 創建column_name為主表名的外鍵
3.alter table table_name
                  add foreign key (列名) references 主表名(主鍵列名) 為已存在的列創建外鍵
4.alter table table_name drop constraint 外鍵約束名 刪除外鍵約束(SQL Server oracle)
5.alter table table_name drop foreign key 外鍵約束名 刪除外鍵約束(Mysql)

 

 

 

5.check 約束
①check約束用於限制列中的值的范圍
②如果對個單個列做check約束,那么該列只可以輸入特定數值
③如果一個表定義check約束,那么此約束會在特定的列對值進行限制
④語法:
1.StudentID int not null check (StudentID>0) 限制StudentID輸入的值要大於0 (SQL Server oracle)
2.StudentID int not null, 限制StudentID輸入的值要大於0 (Mysql)
check (StudentID>0)
3.sex varchar(2) not null check(sex='男' or sex='女') 限制sex的性別只能是男或者女
4.alter table table_name add check(列名>0) 向已有的列加入check約束
5.alter table table_name drop constraint check約束名 刪除約束 約束名可以用 sp_help table_name查看

 

 

 

 

6.default約束
①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 約束名 刪除默認約束

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM