Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

List Foreign Keys referencing tables in SQL Server

Question: How can I list all Foreign Keys Referencing Tables and columns within SQL Server tables? 

Answer: This query will return 6 columns

FOREIGN_KEY = Name of Foreign Key

SCHEMA_NAME = Name of Schema

TABLE = name of table

COLUMN = Column name 

REFERENCED_TBL = the table that has the key column that your FOREIGN_KEY is pointing to

REFERENCED_COL = The column that is the key that your FOREIGN_KEY is pointing to

kkk

use [mydb]

SELECT  obj.name AS FOREIGN_KEY,
    sch.name AS [SCHEMA_NAME],
    tab1.name AS [TABLE],
    col1.name AS [COLUMN],
    tab2.name AS [REFERENCED_TBL],
    col2.name AS [REFERENCED_COL]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
	order by tab1.name

Read More on SQL Keys 

How to drop a SQL column and find foreign keys with sp_fkeys

Natural key versus Surrogate key on a 1 column table



This post first appeared on SQLSERVER-DBA.com, please read the originial post: here

Share the post

List Foreign Keys referencing tables in SQL Server

×

Subscribe to Sqlserver-dba.com

Get updates delivered right to your inbox!

Thank you for your subscription

×