Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Effectively mapping primary key – foreign key relations

By John Liu,

To properly locating the primary key - foreign key relations in a database sounds like a tough task. Mohit Nayyar posted a technique to find out primary key and foreign key that have the same column names. The limitation of that is that, in reality, column names are not always the same in a database. For example, in the AdvantureWorks sample database in SQL2005, the SalesPersonID in Sales.SalesPerson table has a foreign key reference to the EmployeeID column in the HumanResources.Employee table.

This script will map the primary key and foreign key, regardless if the column names are same or not. This script has been tested on both SQL2000 and 2005. This is another evidence of the usefulness of the information_schema view.

If you are interest in a particular column, simple add " and ccu.column_name='<column name>'" in the where cluse.

Mohit's Column:

By John Liu, 2007/11/07

Total article views: 2816 | Views in the last 30 days: 5
Related Articles

Primary-Foreign Key

Primary-Foreign Key


Columns Explorer - With constraints create / drop scripts (no cursors)

Gets all columns infos, foreign keys (multicolumn fk handled), referenced primary keys, default and ...



I would like to ALTER Primary Column data type to INT from NUMERIC. Foreign key relationships are th...


working with primary key column

working with primary key column


Primary and foreign keys

Can a primary key be a foreign key too?


Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones