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

前端 未结 15 756
再見小時候
再見小時候 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:04

    try the following query.

    select object_name(sfc.constraint_object_id) AS constraint_name,
           OBJECT_Name(parent_object_id) AS table_name ,
           ac1.name as table_column_name,
           OBJECT_name(referenced_object_id) as reference_table_name,      
           ac2.name as reference_column_name
    from  sys.foreign_key_columns sfc
    join sys.all_columns ac1 on (ac1.object_id=sfc.parent_object_id and ac1.column_id=sfc.parent_column_id)
    join sys.all_columns ac2 on (ac2.object_id=sfc.referenced_object_id and ac2.column_id=sfc.referenced_column_id) 
    where sfc.parent_object_id=OBJECT_ID(
    );

    this will give the constraint_name, column_names which will be referring and tables which will be depending on the constraint will be there.

提交回复
热议问题