SQL语句修改表结构和添加约束

本文详细介绍了使用SQL语句进行表结构修改的方法,包括删除、添加、修改字段,添加各种约束如主键、唯一性、检查、非空及外键约束,并展示了如何处理约束的级联操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--1.删除一列

alter table TbStudent drop column stuPhone

--2.添加一列

alter table TbStudent add  stuPhone char(11)

--3.修改字段的数据类型(表中Gender列不能有数据)

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_TbStudent_stuName unique(stuName)

--6.添加check约束

alter table TbStudent add constraint CK_TbStudent_stuAge

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

foreign key(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_stuAge

 --12.添加一条语句,添加多个约束

  alter table TbStudent add

  constraint FK_TbStudent_stuClassId foreign key(stuClassId) references TbClass(clsId)

  constraint PK_TbStudent_stuId primary key(stuId)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值