Solved

TSQL question:  List of foreign keys in tables

Posted on 2016-11-18
2
47 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:knowlton
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:knowlton
ID: 41896265
Great!  Thanks!
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Scenario:  You do full backups to a internal hard drive in either product (SBS or Server 2008).  All goes well for a very long time.  One day, backups begin to fail with a message that the disk is full.  Your disk contains many, many more backups th…
You might have come across a situation when you have Exchange 2013 server in two different sites (Production and DR). After adding the Database copy in ECP console it displays Database copy status unknown for the DR exchange server. Issue is strange…
This tutorial will show how to push an installation of Backup Exec to an additional server in both 2012 and 2014 versions of the software. Click on the Backup Exec button in the upper left corner. From here, select Installation and Licensing, then I…
This tutorial will show how to configure a single USB drive with a separate folder for each day of the week. This will allow each of the backups to be kept separate preventing the previous day’s backup from being overwritten. The USB drive must be s…

789 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