SQL儲存過程之刪除指定表中指定字段所有約束

2021-06-06 02:28:31 字數 1964 閱讀 5364

create procedure dropconstraint

@tb varchar(100),@fd varchar(100)

asdeclare @tbname sysname,@fdname sysname

select @tbname=@tb --要處理的表名

,@fdname=@fd --要處理的欄位名

--定義刪除處理的語句

declare tb cursor local for

--預設值約束

select sql='alter table ['+b.name+'] drop constraint ['+d.name+']'

from syscolumns a

join sysobjects b on a.id=b.id and a.name=@fdname and b.name=@tbname

join syscomments c on a.cdefault=c.id

join sysobjects d on c.id=d.id

union --外來鍵引用

select s='alter table ['+c.name+'] drop constraint ['+b.name+']'

from sysforeignkeys a

join sysobjects b on b.id=a.constid

join sysobjects c on c.id=a.fkeyid

join syscolumns d on d.id=c.id and a.fkey=d.colid and d.name=@fdname

join sysobjects e on e.id=a.rkeyid and e.name=@tbname

join syscolumns f on f.id=e.id and a.rkey=f.colid

union --主鍵/唯一鍵/索引

select case when e.xtype in('pk','uq') then 'alter table ['+c.name+'] drop constraint ['+e.name+']'

else 'drop index ['+c.name+'].['+a.name+']' end

from sysindexes a

join sysindexkeys b on a.id=b.id and a.indid=b.indid

join sysobjects c on b.id=c.id and c.xtype='u' and c.name=@tbname

join syscolumns d on b.id=d.id and b.colid=d.colid and d.name=@fdname

left join sysobjects e on e.id=object_id(a.name)

where a.indid not in(0,255)

--執行刪除

declare @s varchar(8000)

open tb

fetch next from tb into @s

while @@fetch_status=0

begin

exec(@s)

fetch next from tb into @s

end

close tb

deallocate tb

先執行上面的sql語句,建立儲存過程,然後再執行儲存過程即可,如:

--刪除字段約束(表,列)

exec dbo.dropconstraint 'table','minute'

exec dbo.dropconstraint 'table','hour'

exec dbo.dropconstraint 'table','day'

go

刪除鍊錶中指定節點

刪除鍊錶中指定節點 思路 利用其他結構 這裡利用棧結構 存放鍊錶中除要刪除的節點外的其他節點。依次將鍊錶元素放入棧中,當遇到要刪除的元素時跳過,最後將棧中元素重新連線成鍊錶。具體 public class removevalue public static node remove node head...

刪除鍊錶中指定的元素

1 新建鍊錶 2 輸出鍊錶 3 刪除鍊錶中的指定元素 include include include include test1.h 建立乙個結構體 typedef struct node node int count 0 記錄鍊錶的長度 node initlist 在迭代插入新的節點的過程中一直使...

sqlserver 刪除表中 指定字串

源表t 單據編號 航班計畫日期 航班號 起飛航站 降落航站 c 026413700 2013 2 11 ca1231 pek xiy c 026413699 2013 2 11 ca1231 pek xiy c 026413698 2013 2 11 ca1231 pek xiy c 0264136...