How can I find out what FOREIGN KEY constraint references a table in SQL Server?

前端 未结 15 833
再見小時候
再見小時候 2020-12-04 05:12

I am trying to drop a table but getting the following message:

Msg 3726, Level 16, State 1, Line 3
Could not drop object \'dbo.UserProfile\' bec

15条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 06:01

    Here it is:

    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) = 'YourTableName'
    

    This way, you'll get the referencing table and column name.

    Edited to use sys.tables instead of generic sys.objects as per comment suggestion. Thanks, marc_s

提交回复
热议问题