删除具有约束constraint列的方法---T-sql
2010-04-20 10:26
190 查看
当删除一个表中的一个字段,恰好这个字段有默认值或是外键等约束的话,直接删除会报错
Msg 5074, Level 16, State 1, Line 32
The object 'DF__tmpTblFor__Incre__3D6081D7' is dependent on column 'ExampleColumn'.
Msg 4922, Level 16, State 9, Line 32
ALTER TABLE DROP COLUMN IncreaseApplies failed because
one or more objects access this column.
采用一下sql语句可以完全将此字段的所有关系删除并从当前表中删除此字段
-- first define variables
declare @default sysname, @sql nvarchar(max)
-- get name of default constraint
select @default = name
from sys.default_constraints
where parent_object_id = object_id('TABLE_NAME')
AND type = 'D'
AND parent_column_id = (
select column_id
from sys.columns
where object_id = object_id('TABLE_NAME')
and name = 'COLUMN_NAME'
)
-- create alter table command as string and run it
set @sql = N'alter table TABLE_NAME drop constraint ' + @default
exec sp_executesql @sql
-- now we can finally drop column
ALTER TABLE [TABLE_NAME]
DROP COLUMN COLUMN_NAME
Msg 5074, Level 16, State 1, Line 32
The object 'DF__tmpTblFor__Incre__3D6081D7' is dependent on column 'ExampleColumn'.
Msg 4922, Level 16, State 9, Line 32
ALTER TABLE DROP COLUMN IncreaseApplies failed because
one or more objects access this column.
采用一下sql语句可以完全将此字段的所有关系删除并从当前表中删除此字段
-- first define variables
declare @default sysname, @sql nvarchar(max)
-- get name of default constraint
select @default = name
from sys.default_constraints
where parent_object_id = object_id('TABLE_NAME')
AND type = 'D'
AND parent_column_id = (
select column_id
from sys.columns
where object_id = object_id('TABLE_NAME')
and name = 'COLUMN_NAME'
)
-- create alter table command as string and run it
set @sql = N'alter table TABLE_NAME drop constraint ' + @default
exec sp_executesql @sql
-- now we can finally drop column
ALTER TABLE [TABLE_NAME]
DROP COLUMN COLUMN_NAME
相关文章推荐
- 约束(Constraint)是Microsoft SQL Server 提供的自动保持数据库完整性的一种方法
- 删除SQL约束的方法
- 用Sql添加删除字段,判断字段是否存在的方法
- sql表删除列的default约束有效方法
- sql语句删除数据表重复字段的方法
- sql删除表中的记录的方法
- 使用SQL语句创建和删除约束
- SQL查询重复记录、删除重复记录方法
- 在SQL中删除重复记录(多种方法)
- 在创建外键约束的时候, 设置级联删除为SET NULL执行sql语句的时候显示有错误,(数据库为sqlserver2000)?
- db2中自增id违反唯一性约束解决方法(SQLCODE=-803, SQLSTATE=23505)
- SQL删除重复数据方法
- SQL基础--> 约束(CONSTRAINT)
- 在SQL中删除重复记录(多种方法)
- 用sql删除数据库重复的数据的方法
- 创建与删除SQL约束或字段约束
- SQL语句实现删除ACCESS重复记录的两种方法
- 用SQL语句删除重复记录的四种好方法
- Oracle删除一条SQL在Shared Pool里缓存的执行计划的三种方法
- MySQL导出、删除索引Index和约束的方法