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)

Find Missing Foreign Keys

By submoa,

This script is dependent on how well the developers involved with your database stuck to naming conventions. It's not 100% accurate, but has saved me a lot of time trying to identify missing foreign key constraints.



A lookup table for address types

CREATE TABLE [dbo].[AddressType](
[AddressTypeID] [tinyint] NOT NULL,
[AddressTypeDesc] [nvarchar](20) NOT NULL,
[AddressTypeID] ASC


A table containing addresses for customers

CREATE TABLE [dbo].[Address](
[AddressID] [int] IDENTITY(1,1) NOT NULL,
[AddressLine1] [nvarchar](50) NOT NULL,
[AddressLine2] [nvarchar](50) NULL,
[City] [nvarchar](50) NOT NULL,
[StateorProvince] [nvarchar](50) NOT NULL,
[Zip] [nvarchar](10) NOT NULL,
[Country] [nvarchar](50) NULL,
[County] [nvarchar](20) NULL,
[CustomerID] [int] NULL,
[AddressTypeID] [tinyint] NULL,
[AddressID] ASC


Based on naming convention, the script combined with the view it creates would know that the column [Address].[AddressTypeID] should have a fkey pointing to the address type lookup table. It knows based in information_schema that the key doesn't yet exist. It will then print the script to the output window.

Total article views: 1226 | Views in the last 30 days: 2
Related Articles

constraints on columns while creating the table

constraints on columns while creating the table


Creating a Check Constraint

Check Constraint


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

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


Unique Constraint

Unique Constraint


Ordereing an IP address

filed is nvarchar

foreign keys (fk)    

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