Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

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' because it is referenced by a FOREIGN KEY constraint.

Msg 2714, Level 16, State 6, Line 2

There is already an object named 'UserProfile' in the database.

I looked around with SQL Server Management Studio but I am unable to find the constraint. How can I find out the foreign key constraints?

1 Answer

0 votes
by (40.7k points)

Try using the below 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) = 'YourTableName'

The above query will help you to get the referencing table and column name.

Note: You can use sys.tables instead of generic sys.objects.

Related questions

0 votes
1 answer
0 votes
1 answer

Browse Categories

...