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

后端 未结 26 2699
梦毁少年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 08:05

    List of all foreign keys referencing a given table in SQL Server :

    You can get the referencing table name and column name through following query...

    SELECT 
       OBJECT_NAME(f.parent_object_id) TableName,
       COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
    FROM 
       sys.foreign_keys AS f
    INNER JOIN 
       sys.foreign_key_columns AS fc 
          ON f.OBJECT_ID = fc.constraint_object_id
    INNER JOIN 
       sys.tables t 
          ON t.OBJECT_ID = fc.referenced_object_id
    WHERE 
       OBJECT_NAME (f.referenced_object_id) = 'TableName'
    

    And following screenshot for your understanding...

提交回复
热议问题