create table Employees( EmpId int identity(1,1), EmpName varchar(50), EmpGender char(2), EmpAge int, EmpEmail varchar(100), EmpAddress varchar(500) ) go 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 varchar(1000) --手动修改一下EmpEmail的数据类型(varchar(200)) alter table Employess alter column EmpAddr varchar(200) --为EmpId增加一个主键约束 alter table Employess add constraint PK_Employees_EmpId primary key(EmpId) --增加yi8ge非空约束 其实即使修改列 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 --为年龄增加一个检查约束;年龄必须在0-120岁之间含0和120岁 alter table Employess add constraint CK_Employees_EmpAge check(empage>=0 and empage<=120) --增加外键约束,表Employee中有一列EmpDeptId引用TblDepartment表中的DeptId alter table Employees add DepId int not null alter table Department add constraint PK_Department_DepId primary key(DepId) alter table Employees add constraint FK_Employees_Department foreign key(DepId) references Departmnet(DepId) --增加外加约束时,设置级联更新,级联删除 --[ON DELETE{NOACTION|SET NULL|DEFAULT}] --[ON UPDATE{NOACTION|SET NULL|DEFAULT}] --先删除原来的外键 alter table Employees drop constraint FK_Employees_Department --设置外键的时候设置级联删除 alter table Employees add constraint FK_Employees_Department foreign key(DepId) references Departmnet(DepId) on delete cascade --删除某个名字的约束 alter table Employees drop constraint FK_Employees_Department --一条语句删除多个约束,约束名用 逗号 隔开 alter table Employees drop constraint FK_Employees_Department,CK_Emplpoyees_EmpAge,UQ_Employees_EmpName --一条语句增加多个约束 alter table Employees add constraint UQ_Emplyees_EmpName unique(EmpName), constraint CK_Emplyees_EmpAge check(EmpAge>=0 and EmpAge<=120)