/*初始化两张表,测试添加约束语句*/
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约束
|