How to drop all Foreign Key constraints in all tables?

后端 未结 7 1246
难免孤独
难免孤独 2020-12-08 10:03

I want to write sql command to drop all constraints in all tables. I searched on the internet and found the following which works fine if the database is small and not compl

7条回答
  •  我在风中等你
    2020-12-08 10:44

    Here's a short and sweet script I use (on SQL Server 2008 and up) to remove all foreign keys that also takes into account the object's schema:

    declare @sql varchar(max) = (
        select 
            'alter table ' + quotename(schema_name(schema_id)) + '.' +
            quotename(object_name(parent_object_id)) +
            ' drop constraint '+quotename(name) + ';'
        from sys.foreign_keys
        for xml path('')
    );
    exec sp_executesql @sql;
    

提交回复
热议问题