如果这个表的这一列有默认值约束,那么如果直接删除就会报错
这里有两个办法
1.如果创建列的时候给默认约束设置了名字,直接删除该约束
如果是系统默认命名,那么就先获取默认约束名,
删除约束后,就可以直接删除列
--创建一个带默认值列
alter table dbo.Student
add test2 int not NULL default 0
--尝试删除
alter table dbo.Student
drop column test2
-- 报错
-- 对象'DF__Student__test2__3A81B327' 依赖于 列'test2'。
-- 消息 4922,级别 16,状态 9,第 1 行
-- 由于一个或多个对象访问此列,ALTER TABLE DROP COLUMN test2 失败。
-- 查询该表的所有信息
sp_help 'dbo.Student'
-- 找到约束后查询
alter table dbo.Student
drop column test2
drop constraint DF__Student__test2__37A5467C
-- 再次删除发现成功
alter table dbo.Student
drop column test22.上边的方法显然不方便
这里有一个脚本专门删除列的默认约束
--只要改两个参数
declare @tablename varchar(100), @columnname varchar(100), @tab varchar(100)
set @tablename = 'Student' --表名(不要加多余的东西)
set @columnname= 'test2' --字段名称
declare @defname varchar(100) --约束名称
declare @cmd varchar(100) --构造的SQL语句
select @defname = name from sysobjects so join sysconstraints sc on so.id = sc.constid where object_name(so.parent_obj) = @tablename
and so.xtype = 'd' and sc.colid =(select colid from syscolumns where id = object_id(@tablename) and name = @columnname)
select @cmd= 'alter table '+ @tablename+ ' drop constraint '+ @defname if @cmd is null print ' no default constraint to drop'
exec (@cmd)
-- 直接删除列
alter table dbo.Student
drop column test2
本文介绍在SQL Server中删除带有默认约束的列的两种方法:一是手动删除约束,二是使用脚本自动删除。文章详细展示了如何通过查询表信息来定位并删除指定的默认约束,以便后续能够顺利删除列。


被折叠的 条评论
为什么被折叠?



