Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
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.

 

Example:

A lookup table for address types

CREATE TABLE [dbo].[AddressType](
[AddressTypeID] [tinyint] NOT NULL,
[AddressTypeDesc] [nvarchar](20) NOT NULL,
CONSTRAINT [PK_AddressType] PRIMARY KEY CLUSTERED
(
[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,
CONSTRAINT [PK_Address_1] PRIMARY KEY NONCLUSTERED
(
[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: 1235 | Views in the last 30 days: 1
 
Related Articles
FORUM

constraints on columns while creating the table

constraints on columns while creating the table

FORUM

Creating a Check Constraint

Check Constraint

SCRIPT

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

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

FORUM

Unique Constraint

Unique Constraint

FORUM

Ordereing an IP address

filed is nvarchar

Tags
foreign keys (fk)    
utility    
 
Contribute