Solved

TSQL question:  List of foreign keys in tables

Posted on 2016-11-18
2
55 Views
Last Modified: 2017-01-05
It is possible to query a database and discover all tables that use a particular foreign key?

For example, table "Entity" has a primary key called "iEntityId"

Other tables reference this column, but I don't know which ones.  I am wanting to find out programmatically.

Possible in T-SQL?
0
Comment
Question by:Tom Knowlton
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 28

Accepted Solution

by:
Pawan Kumar earned 500 total points
ID: 41893864
Try.

Use two system tables - sys.foreign_keys & sys.foreign_key_columns

SELECT OBJECT_NAME(fk.parent_object_id) tabName , 'iEntityId' colName 
FROM sys.foreign_keys fk CROSS APPLY
(
	SELECT fkc.parent_object_id,fkc.parent_column_id FROM sys.foreign_key_columns fkc 
	WHERE fk.OBJECT_ID = fkc.constraint_object_id 
	AND COL_NAME(fkc.parent_object_id,fkc.parent_column_id) = 'iEntityId'
) k 

Open in new window


Hope it helps !
0
 
LVL 5

Author Closing Comment

by:Tom Knowlton
ID: 41896265
Great!  Thanks!
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I was asked if I could set up a fax machine so that incoming faxes were delivered to people's Exchange inboxes and so that they could send faxes from their desktops without needing to print the document first.  I knew it was possible but I had no id…
I was supporting a handful of Windows 2008 (non-R2) 2 node clusters with shared quorum disks. Some had SQL 2008 installed and some were just a vendor application that we supported. For the purposes of this article it doesn’t really matter which so w…
This tutorial will give a short introduction and overview of Backup Exec 2012 and how to navigate and perform basic functions. Click on the Backup Exec button in the upper left corner. From here, are global settings for the application such as conne…
This tutorial will walk an individual through setting the global and backup job media overwrite and protection periods in Backup Exec 2012. Log onto the Backup Exec Central Administration Server. Examine the services. If all or most of them are stop…

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question