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

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

    if you want to go via SSMS on the object explorer window, right click on the object you want to drop, do view dependencies.

    0 讨论(0)
  • 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(<main table name>);
    

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

    0 讨论(0)
  • 2020-12-04 06:08

    Another way is to check the results of

    sp_help 'TableName'
    

    (or just highlight the quoted TableName and pres ALT+F1)

    With time passing, I just decided to refine my answer. Below is a screenshot of the results that sp_help provides. A have used the AdventureWorksDW2012 DB for this example. There is numerous good information there, and what we are looking for is at the very end - highlighted in green:

    0 讨论(0)
提交回复
热议问题