sql語句修改表結構和添加約束

sql語句修改表結構和添加約束

create table Tbclass
(
	clsId int primary key identity(1,1),
	clsName nvarchar(8) unique,
	clsTeacher nvarchar(4),
	clsNumber smallint check(clsNumber >= 20 and clsNumber <= 80)
)
create table TbStudent
(
	stuId int identity(1,1) primary key,
	stuName nvarchar(4) not null,
	stuNumber char(9) unique,
	stuGender bit default(1),
	stuAddress nvarchar(32),
	stuAge smallint,
	stuPhone char(11),
	stuClassId int foreign key references  Tbclass(clsId)

)

以下操作是在上面建的表的前提下完成的

1.刪除一列

alter table TbStudent drop column stuPhone

2.添加一列

alter table TbStudent add  stuPhone char(11)

3.修改字段的數據類型

alter table TbStudent alter column stuGender nchar(1)

4.添加主鍵約束

alter table TbStudent add constraint Pk_TbStudent_StuId primary key(StuId)

5.添加唯一性約束

alter table TbStudent add constraint UK_TbStdent_StuName unique(stuName)

6.添加check約束

alter table TbStudent add constraint CK_TbStudent_StuAge
check(stuAge>=20 and stuAge <=30)

7.非空約束,實際上就是對列的數據類型修改

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

8.添加外鍵約束

alter table TbStudent add constraint FK_TbStudent_stuClassId 
foreign key(stuClassId) references Tbclass(clsId)

9.外鍵的級聯 刪除或更新

--級聯刪除
alter table TbStudent add constraint FK_TbStudent_stuClassId 
foreign key(stuClassId) references Tbclass(clsId) on delete cascade 
--級聯更新
alter table TbStudent add constraint FK_TbStudent_stuClassId 
foreign key(stuClassId) references Tbclass(clsId) on update cascade 

10.刪除約束

alter table TbStudent drop constraint FK_TbStudent_stuClassId
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章