--通过t-sql语句来创建约束
------------------------------------------------------------
--新建一张表:员工信息表
create table Employees
(
EmpId int identity(1,1),
EmpName varchar(50),
EmpGender char(2),
EmpAge int,
EmpEmail varchar(100),
EmpAddress varchar(500)
)
create table Department
(
DepId int identity(1,1) ,
DepName varchar(50)
)
--=====手动增加约束==========
--手动删除一列(删除EmpAddress列)
alter table Employees drop column EmpAddress
--手动增加一列(增加一列EmpAddr varchar(1000))
alter table Employees add EmpAddr nvarchar(1000)
--手动修改一下EmpEmail的数据类型(varchar(200))
alter table Employees alter column EmpEmail varchar(200)
--为EmpId增加一个主键约束
alter table Employees add constraint PK_Employees_EmpId primary key(EmpId)
--非空约束,为EmpName增加一个非空约束 not null(修改列)
alter table Employees alter column EmpName varchar(50) not null
--为EmpName增加一个唯一约束
alter table Employees add constraint UQ_Employees_EmpName unique(EmpName)
--为性别增加一个默认约束,默认为‘男‘
alter table Employees add constraint DF_Employees_EmpGender default(‘男‘) for EmpGender
--为性别增加一个检查约束,要求性别只能是:‘男‘ or ‘女‘
alter table Employees add constraint CK_Employees_EmpGender check(EmpGender=‘男‘ or EmpGender=‘女‘)
--为年龄增加一个检查约束:年龄必须在-120岁之间,含岁与岁。
alter table Employees add constraint CK_Employees_EmpAge check(EmpAge>=0 and EmpAge<=120)
--创建一个部门表,然后为Employee表增加一个DepId列。
alter table Employees add EmpDepId int not null
--为Department表设置主键。主键列是:DepId
alter table Department add constraint PK_Department_DepId primary key(DepId)
--增加外键约束
alter table Employees add constraint FK_Employees_Department foreign key(EmpDepId) references Department(DepId) -- on delete cascade
--删除约束
alter table Employees drop constraint
FK_Employees_Department,
CK_Employees_EmpAge,
CK_Employees_EmpGender,
DF_Employees_EmpGender,
UQ_Employees_EmpName
--通过一条代码来增加多个约束
alter table Employees add
constraint FK_Employees_Department foreign key(EmpDepId) references Department(DepId),
constraint CK_Employees_EmpAge check(EmpAge>=0 and EmpAge<=120),
constraint CK_Employees_EmpGender check(EmpGender=‘男‘ or EmpGender=‘女‘)
---创建表的同时就为表增加约束
create table Employees
(
EmpId int identity(1,1) primary key,
EmpName varchar(50) not null unique check(len(EmpName)>2),
EmpGender char(2) default(‘男‘),
EmpAge int check(EmpAge>0 and EmpAge<120),
EmpEmail varchar(100) unique,
EmpAddress varchar(500) not null,
EmpDepId int foreign key references Department(DepId) on delete cascade
)
create table Department
(
DepId int identity(1,1) primary key,
DepName varchar(50) not null unique
)