SQL使用代码创建数据完整性,约束

--使用代码创建数据完整性:
--主键约束(primary key PK) 唯一键约束(unique UQ) 默认值约束(default DF) check约束(check CK) 主外键约束(foreign key FK)
--语法:
--alter table 表名
--add constraint 约束名称(前缀+自定义名称) 约束类型 约束说明(字段名称 表达式 值)
--为Id设置主键约束
alter table tracher
add constraint PK_Teacher_Id primary key(id)

--为Email添加唯一键约束
if exists (select*from sysobjects where name='UQ_Teacher_Email')
alter table teacher drop constraint UQ_Teacher_Email
go
alter table tracher
add constraint UQ_Teacher_Email unique(email)
--为工资添加默认值,为年龄添加check约束
alter table Teacher
add constraint Df_Teacher_Salary default(5000) for salary,
constraint CK_Tracher_Age check(age>0 and age<=100)

--添加主键约束
alter table Teacher
add constraint FK_Tracher_Classes_Classid foreign key(classid) references classes(cid)
alter table tracher
add constraint PK_Teacher_id primary key(id)

if exists(select*from sysobjects where name='UQ_Teacher_Email')
alter table teacher drop constraint UQ_teacher_Email

alter table tracher
add constraint UQ_teacher_Email unique(email)

alter table Teacher
add constraint PK_teacher_id primary key (id)

alter table Teacher
add constraint DF_teacher_salary default (5000) for salary

alter table Teacher
add constraint UQ_teacher_Email unique(email)
alter table Teacher
add constraint CK_Teacher_Age check(age>0and age<100)

alter table teacher
add constraint FK_teacher_classes_classid foreign key(classid) references classes(id)

转载于:https://www.cnblogs.com/dianshen520/p/4351839.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值