Skip to content
Advertisement

How to find out where reference to primary key is used in SQL Server?

I have a table in SQL Server 2008 R2 with primary key called ID which then is used by multiple tables around the database as foreign key. How to find out by which tables it is used? I’m trying to delete that record but it’s complaining that ID is in use.

Or maybe there’s an easy way to delete all referenced records from whole database just by giving database that ID? Right now I’m going for each table (that I know has that ID as foreign key) and deleting records that correspond to that particular ID but if there’s better/simpler way to find it and delete all at once with simple code then that would best idea.

Advertisement

Answer

MS SQL benefits from being able to describe itself. In particular, there is a series of views that begin with INFORMATION_SCHEMA.

To get an idea of where your field is used, try :-

SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement