Solved

TSQL question:  List of foreign keys in tables

Posted on 2016-11-18
2
17 Views
Last Modified: 2016-11-21
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 17

Accepted Solution

by:
Pawan Kumar Khowal earned 500 total points
Comment Utility
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
Comment Utility
Great!  Thanks!
0

Featured Post

The problems with reply email signatures

Do you wish that you could place an email signature under a reply? Well, unfortunately, you can't. That great Exchange/Office 365 signature you've created will just appear at the bottom of an email chain. What a pain! Is there really no way to solve this? Well, there might be...

Join & Write a Comment

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…
OfficeMate Freezes on login or does not load after login credentials are input.
This tutorial will walk an individual through the steps necessary to enable the VMware\Hyper-V licensed feature of Backup Exec 2012. In addition, how to add a VMware server and configure a backup job. The first step is to acquire the necessary licen…
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…

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now