创建表添加约束

use mysms
go
--sysobjects:保存当前数据库中的所有数据表信息
if exists(select * from sysobjects where name='emp')
drop table emp
go
create table emp
(
empno int not null,
ename varchar(20) not null,
sex varchar(2),
birthday datetime,
deptno int not null
)
if exists(select * from sysobjects where name='dept')
drop table dept
go
--创建 数据表 数据名
create table dept
(
deptno int identity(1,1) primary key,--字段名 数据类型 约束
dname varchar(20) not null,
phone varchar(11),--字段名 数据类型
loc varchar(20)
)

--主键约束
--修改 表格 表名 添加 约束 约束名 约束
alter table emp add constraint pk_emp primary key(empno)
--唯一约束
alter table dept add constraint uq_dept_dname unique(dname)
--检查约束
alter table emp add constraint ck_emp_sex check(sex in ('男','女'))
--默认约束
alter table dept add constraint df_dept_loc default ('长沙') for loc
insert into dept values('开发部','12345678',default)
--外键约束
alter table emp add constraint fk_dept_emp
--外 键(外键列) 参考 主表(主键列)
Foreign key(deptno) REFERENCES dept(deptno)

原文地址:https://www.cnblogs.com/kite/p/3615649.html