oracle去掉默认值sql,如何在T-SQL中删除默认值或类似约束?

这个博客分享了一段SQL脚本,用于在表中删除指定列的同时,自动处理与该列相关的所有依赖约束,包括默认约束和检查约束。脚本首先获取受影响的约束,然后构建一个ALTERTABLE语句来一次性删除这些约束和列,并执行该语句。
摘要由CSDN通过智能技术生成

这里有我自己的版本,它会删除所有依赖的约束 – 默认约束 (如果存在的话)和所有受影响的检查约束 (正如SQL标准似乎暗示的一样,和其他一些数据库似乎是这样)

declare @constraints varchar(4000); declare @sql varchar(4000); with table_id_column_position as ( select object_id table_id, column_id column_position from sys.columns where object_id is not null and object_id = object_id('TableName') and name = 'ColumnToBeDropped' ) select @constraints = coalesce(@constraints, 'constraint ') + '[' + name + '], ' from sysobjects where ( -- is CHECK constraint type = 'C' -- dependeds on the column and id is not null and id in ( select object_id --, object_name(object_id) from sys.sql_dependencies, table_id_column_position where object_id is not null and referenced_major_id = table_id_column_position.table_id and referenced_minor_id = table_id_column_position.column_position ) ) OR ( -- is DEFAULT constraint type = 'D' and id is not null and id in ( select object_id from sys.default_constraints, table_id_column_position where object_id is not null and parent_object_id = table_id_column_position.table_id and parent_column_id = table_id_column_position.column_position ) ); set @sql = 'alter table TableName drop ' + coalesce(@constraints, '') + ' column ColumnToBeDropped'; exec @sql

(注意:在上面的代码中, TableName和ColumnToBeDropped都会出现两次)

这通过构build单个ALTER TABLE TableName DROP CONSTRAINT c1, ..., COLUMN ColumnToBeDropped并执行它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值