有关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


对我的博客有什么好的意见或者有什么问题还希望读者朋友们慷慨的说出来,同时感谢你的帮助为我带来的成长,愿同样渴望优秀的您学业有成,心想事成!!!

猜你喜欢

转载自blog.csdn.net/vlllllv/article/details/80150942