How can I list all foreign keys referencing a given table in SQL Server?

后端 未结 26 3264
梦毁少年i
梦毁少年i 2020-11-22 07:13

I need to remove a highly referenced table in a SQL Server database. How can I get a list of all the foreign key constraints I will need to remove in order to drop the tabl

26条回答
  •  星月不相逢
    2020-11-22 07:58

    The original question asked to get a list of all foreign keys into a highly referenced table so that the table can be removed.

    This little query returns all the 'drop foreign key' commands needed to drop all foreign keys into a particular table:

    SELECT 
       'ALTER TABLE ['+sch.name+'].['+referencingTable.Name+'] DROP CONSTRAINT ['+foreignKey.name+']' '[DropCommand]'
    FROM sys.foreign_key_columns fk
        JOIN sys.tables referencingTable ON fk.parent_object_id = referencingTable.object_id
        JOIN sys.schemas sch ON referencingTable.schema_id = sch.schema_id
        JOIN sys.objects foreignKey ON foreignKey.object_id = fk.constraint_object_id
        JOIN sys.tables referencedTable ON fk.referenced_object_id = referencedTable.object_id
    WHERE referencedTable.name = 'MyTableName'
    

    Example output:

    [DropCommand]
    ALTER TABLE [dbo].[OtherTable1] DROP CONSTRAINT [FK_OtherTable1_MyTable]
    ALTER TABLE [dbo].[OtherTable2] DROP CONSTRAINT [FK_OtherTable2_MyTable]
    

    Omit the WHERE-clause to get the drop commands for all foreign keys in the current database.

提交回复
热议问题