建立表添加約束

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)ide

相關文章
相關標籤/搜索