Click here to Skip to main content
15,885,546 members
Articles / Database Development / SQL Server
Tip/Trick

List Primary Key and Foreign Key Relationship in Database - SQL Server

Rate me:
Please Sign up or sign in to vote.
3.65/5 (9 votes)
6 Oct 2016CPOL 42.8K   11   3
Display the list of all Tables, the Referenced columns, the Referencing Table, the Referencing columns and the Constraint name in a database

Introduction

Here's a quick SQL Server tip for displaying all the Primary key foreign key relationship from a database. For this table, I am using the AdventureWorks2012 database.

1. For all tables in a database, below is the query.

SELECT o2.name AS Referenced_Table_Name,
       c2.name AS Referenced_Column_As_FK,
       o1.name AS Referencing_Table_Name,
       c1.name AS Referencing_Column_Name,
s.name AS Constraint_name
FROM  sysforeignkeys fk
INNER JOIN sysobjects o1 ON fk.fkeyid = o1.id
INNER JOIN sysobjects o2 ON fk.rkeyid = o2.id
INNER JOIN syscolumns c1 ON c1.id = o1.id AND c1.colid = fk.fkey
INNER JOIN syscolumns c2 ON c2.id = o2.id AND c2.colid = fk.rkey
INNER JOIN sysobjects s ON fk.constid = s.id
ORDER BY o2.name

Here's the output:

Image 1

2. For a specific table in a database, below is the query.

SELECT o2.name AS Referenced_Table_name,  
       c2.name AS Referenced_Column_Name,  
       o1.name AS Referencing_Table_name,  
       c1.name AS Referencing_column_Name,  
       s.name AS Constraint_name  
FROM sysforeignkeys fk  
INNER JOIN sysobjects o1 ON fk.fkeyid = o1.id  
INNER JOIN sysobjects o2 ON fk.rkeyid = o2.id  
INNER JOIN syscolumns c1 ON c1.id = o1.id AND c1.colid = fk.fkey  
INNER JOIN syscolumns c2 ON c2.id = o2.id AND c2.colid = fk.rkey  
INNER JOIN sysobjects s ON fk.constid = s.id  
WHERE o2.name='Product'  -- Replace the Table_Name with actual DB Table name  

Here's the output:

Image 2

There's also a command:

exec sp_fkeys @pktable_name ='Product',
        @pktable_owner ='Production'

And here's the output:

Image 3

Hope this helps.

Thanks for reading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United States United States
Husband, Father, TheWorkingProgrammer

Comments and Discussions

 
Question[My vote of 2] Wy do you use the old system views? Pin
Malte Klena12-Oct-16 0:24
Malte Klena12-Oct-16 0:24 
AnswerRe: [My vote of 2] Wy do you use the old system views? Pin
Hussain Patel12-Oct-16 6:31
professionalHussain Patel12-Oct-16 6:31 
PraiseNice Pin
SteveHolle16-Sep-16 5:47
SteveHolle16-Sep-16 5:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.