1. 程式人生 > >SQL語句修改表結構和新增約束

SQL語句修改表結構和新增約束

 --修改表結構和追加約束

 --1、刪除一列

 alter table TbStudent drop  column stuPhone

 --2.新增一列

 alter table TbStudent add column stuPhone

 3.修改欄位的資料型別

 alter table TbStudent alter column stuGender nchar(1)

 --4.新增主鍵約束

 alter table TbStudent add constraint PK_TbStudent_Id primary key(stuId)

 --5,新增唯一性約束

 alter

table TbStudent add constraint UK_TbStudent_stuName unqiue(stuName)

 6.新增check約束

 alter table TbStudent add constraint CK_TbStudent_stu_Age

 check(stuAge>=18 and stuAge<=35)

 --7.新增非空約束,實際上就是對列的資料型別修改

 alter table TbStudent alter column stuPhone char(11) not null

 --8.新增外來鍵約束

 alter table

TbStudent add constraint FK_TbStudent_stuClassId

 stuClassId) references TbClass(clsId)

 --9.外來鍵的級聯刪除/更新

 --語法:on delete [no action|cascade]

 --      on update [no action|cascade]

 alter table TbStudent add constraint FK_TbStudent_stuClassId

 foreign key(stuClassId) references TbClass(clsId) on

delete cascade

 --10.刪除約束

 alter table TbStudent drop constraint FK_TbStudent_stuClassId

 --11.一條語句刪除多條約束

 alter table TbStudent drop constraint FK_TbStudent_stuClassId,CK_TbStudent

 --12.一條語句新增多個約束

 alter table TbStudent add

 constraint FK_TbStudent_stuClassID foreign key(stuClassId) references TbClassId

 constraint PK_TbStudent_stuId primary key(stuId)