创建数据表并为已创建的表添加约束

/*初始化两张表,测试添加约束语句*/
use E_Market
go

--创建部门表
if exists(select * from sysobjects where name = 'department')
drop table department
create table department --部门表
(
	DepartmentId char(5) not null primary key,
	DeparmentName varchar(20)
)
--创建员工表
if exists(select * from sysobjects where name = 'employee')
drop table employee
create table employee   --员工表
(
	Id char(18) not null,   --身份证号
	JobId char(6) not null, --员工编号
	Name varchar(20) not null,  --姓名
	Sex char(2) null,   --性别
	Birthday datetime null, --出生日期
	Salary Money not null,  --工资
	DepartmentId char(5) null   --部门编号
)
/*
对员工表要求:
	id的值是唯一,作为  (主键)
	jobid的值也是唯一的,作为为一键  (唯一键)
	sex取值只能为男或女     (检查约束)
	birthday要求必须年满18        (检查约束)
	salary默认值为3000      (默认约束)
	department值必须在department表中存在departmentid(外键)
*/

/*添加主键约束*/
alter table employee
add constraint PK_id primary key(Id)

/*添加唯一约束*/
alter table employee
add constraint UQ_jobid unique(Jobid)

/*添加检查约束*/
alter table employee
 add constraint CK_sex check(sex in('男','女'))

/*添加检查约束*/
alter table employee
add constraint CK_birthday check (year(GETDATE())-year(birthday)>=18)   --表示当前时间减去出生日期时间大于18岁

/*添加默认约束*/
alter table employee
add constraint DF_salray default 3000 for salary

/*添加外键约束*/
alter table employee
add constraint FK_departmentid foreign key (departmentid) references department(departmentid)

/*删除约束*/
alter table employee
drop constraint ck_sex   --删除CK_sex约束


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值