I have one table in the database having ID as the primary key. Now this ID is referenced (as Foreign Key) in many other tables. How can I create a result with each row that whether it is referenced or not. As I want to prevent users from deleting items that have references. So the output should be:
ID Title(Another Column in the table) IsReferenced
-- ---------------------------------- ---------------------------------
1 Title 1 True (or Count any one will work)
2 Title 2 True
3 Title 3 False
4 Title 4 False
Best Answer
Given this data:
You can avoid knowing all of the tables and columns that reference the parent by building dynamic SQL from the metadata about the foreign keys:
When you're happy with the
PRINT
output (if you have tons of foreign keys, it may get truncated; see this tip for ideas), uncomment theEXEC
. My print output looked like this:And when I ran that I got the expected:
Don't forget to clean up tempdb: