How to check if a record key is used in other tables as a foreign key (sql)?

I have a table in which its primary key "ID" is used in many other tables as a foreign key.

How can I understand that a record from this table (for example, the first record "ID = 1") is used in another table?

I do not want to choose from all the other tables to understand why there are so many tables and relationships too. I was looking for a solution, there were no working solutions, or I realized that it was wrong. Please help.

+7
source share
2 answers

For a general way, use this and you will get all tables with a foreign key, and then you can do a loop to check all the tables in the list. This way you can add foreign keys, and no changes to the code are needed ...

SELECT sys.sysobjects.name, sys.foreign_keys.* FROM sys.foreign_keys inner join sys.sysobjects on sys.foreign_keys.parent_object_id = sys.sysobjects.id WHERE referenced_object_id = OBJECT_ID(N'[dbo].[TableName]') 
+8
source

You need to join all other tables. Like this:

 select * from Parents where exists(select * from Children1 where ...) or exists(select * from Children2 where ...) or exists(select * from Children3 where ...) 

If all your FK columns are indexed, it will be extremely efficient. You will get a good merge pool.

+2
source

All Articles