删除表中的所有外键

trn*_*ash 2 t-sql foreign-keys sql-server-2008

我有这个脚本在sql server 2005中工作

-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)

set @database = 'dotnetnuke'
set @table = 'tabs'

DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
    select    @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME 
    from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
    where    constraint_catalog = @database and 
            table_name = @table
    exec    sp_executesql @sql
END
Run Code Online (Sandbox Code Playgroud)

它在SQL Server 2008中不起作用.如何轻松删除某个表的所有外键约束?有没有人有更好的脚本?

小智 7

有一个更简单的方法.那为什么呢?剧本:

select ' alter table ' + schema_name(Schema_id)+'.'+ object_name(parent_object_id)
+ '  DROP CONSTRAINT  ' +  name   from sys.foreign_keys f1
Run Code Online (Sandbox Code Playgroud)

将为所有外键编写drop