有關SQL sever上使用SQL語言創建約束的問題簡單回答

有許多剛接觸SQL sever不久的朋友中有不少人對創建約束犯難,小編在學習初期也和你一樣,於是寫下這篇博客希望能夠爲你減輕一些不必要的痛苦。

創建約束:
1、表和約束同時創建:
create table sller
(

saleid char(5) not null    

Constraint fk_name references table_name--另一個表 (column)   --另一個表的主鍵                                                 --外鍵約束


salename char(8) not null     

Constraint name primary key ,--主鍵約束


sex char(2) 

check(Sex=N'男' or Sex=N'女'),--check約束


birthday datetime 

default((0)), --默認約束


hiredate datetime,    

--加非空約束,不加"not null" 默認爲:可以爲空


address char(60),
telephone char(13),
note char(200)
)
2、在已有的表內創建約束:
(1)、使用SQL語言創建:
創建外鍵約束:Constraint name references table_name  (列)


創建主鍵: alter table sller(選擇表名) add constraint PK_salename(命名約束名) Primary key (salename)(列名)


創建外鍵:

Alter table t1(主鍵表名) add constraint fk_salename(外鍵名) foreign key (salename)(列名) references t2(外鍵名)  (salename)(列名)


創建唯一約束:

alter table t2 add Constraint ik_saleid unique (salename)


創建默認約束:

alter table t3 add Constraint [df_sex](設置約束名) default ('男')(設置約束值) for [sex](選擇約束列)


創建check 約束:
alter table t2(選擇表) add constraint ck_sex check (sex='男' or sex='女')(更規範)
(2)、界面操作操作地址:
https://blog.csdn.net/qq61394323/article/details/26091875

 

 

對我的博客有什麼好的意見或者有什麼問題還希望讀者朋友們慷慨的說出來,同時感謝你的幫助爲我帶來的成長,願同樣渴望優秀的您學業有成,心想事成!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章