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

后端 未结 26 3174
梦毁少年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

     SELECT OBJECT_NAME(fk.parent_object_id) as ReferencingTable, 
            OBJECT_NAME(fk.constraint_object_id) as [FKContraint]
      FROM sys.foreign_key_columns as fk
     WHERE fk.referenced_object_id = OBJECT_ID('ReferencedTable', 'U')
    

    This only shows the relationship if the are foreign key constraints. My database apparently predates the FK constraint.Some table use triggers to enforce referential integrity, and sometimes there's nothing but a similarly named column to indicate the relationship (and no referential integrity at all).

    Fortunately, we do have a consistent naming scene so I am able to find referencing tables and views like this:

    SELECT OBJECT_NAME(object_id) from sys.columns where name like 'client_id'
    

    I used this select as the basis for generating a script the does what I need to do on the related tables.

提交回复
热议问题