使用代码创建SQL约束

使用代码创建SQL约束

  1. 约束的种类
    主键约束(primary key PK) 唯一约束(unique UQ) 检查约束(check CK) 默认值约束(default DF) 外键约束(foreign key FK)

  2. 语法
    alter table 表名称
    add constraint 约束的名称(以简写作为前缀) 约束的类型 约束的说明(字段or表达式or值)

  3. 使用代码创建约束
    使用的数据库

	-- 1、将Id设置为主键
	if exists(select * from sysobjects where name = 'PK_Teacher_Id') 
	alter table Teacher drop constraint PK_Teacher_Id --如果存在已经存在约束PK_Teacher_Id ,则删除
	alter table Teacher 
	add constraint PK_Teacher_Id primary key(Id)
	
	-- 2、将Name设置为唯一键
	if exists(select * from sysobjects where name = 'UQ_Teacher_Name')
	alter table Teacher drop constraint UQ_Teacher_Name  --如果存在已经存在约束UQ_Teacher_Name ,则删除
	alter table Teacher
	add constraint UQ_Teacher_Name unique(Name)
	
	-- 3、将Age添加Check约束
	if exists(select * from sysobjects where name = 'CK_Teacher_Age')
	alter table Teacher drop constraint CK_Teacher_Age --如果存在已经存在约束CK_Teacher_Age ,则删除
	alter table Teacher
	add constraint CK_Teacher_Age check(Age > 0 and Age <= 100)
	
	-- 4、将Birthday添加默认值
	if exists(select * from sysobjects where name = 'DF_Teacher_Birthday')
	alter table Teacher drop constraint DF_Teacher_Birthday --如果存在已经存在约束DF_Teacher_Birthday ,则删除
	alter table Teacher 
	add constraint DF_Teacher_Birthday default('2001-10-10') for Birthday --for说明为那个字段添加默认值

	-- 5、将CId添加外键约束
	if exists(select * from sysobjects where name = 'FK_Teacher_CId')
	alter table Teacher drop constraint FK_Teacher_CId --如果存在已经存在约束FK_Teacher_CId ,则删除
	alter table Teacher
	with nocheck --当增加约束时,已经存在数据,可以设置不检查现有数据
	add constraint FK_Teacher_CId foreign key(CId) references Classes(CId)
  1. 备注
    增加外键约束时,设置级联更新、级联删除
    [on update {no action | cascade | set null | set default }]
    [on delete {no action | cascade | set null | set default }]
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

slb190623

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值