Skip to content

Instantly share code, notes, and snippets.

@kmoormann
Created July 26, 2013 15:45
Show Gist options
  • Save kmoormann/6089935 to your computer and use it in GitHub Desktop.
Save kmoormann/6089935 to your computer and use it in GitHub Desktop.
Determine all foreign keys for a sql server database. Tested on SQL 2008 R2
USE <REPLACE WITH DATABASE NAME>
SELECT
foreignKeyConstraintObject.Name as ForeignKeyConstraint
,foreignKeySchema.Name as ForeignKeySchema
,foreignKeyTable.Name as ForeignKeyTable
,foreignKeyColumn.Name as FoeignKeyName
,referencedSchema.Name as ReferencedSchema
,referencedTable.Name as ReferencedTable
,referencedColumn.Name as ReferencedColumn
FROM sys.foreign_key_columns AS foreignKeyConstraintColumns
INNER JOIN sys.objects AS foreignKeyConstraintObject
ON foreignKeyConstraintColumns.constraint_object_id = foreignKeyConstraintObject.object_id
INNER JOIN sys.tables AS foreignKeyTable
ON foreignKeyConstraintColumns.parent_object_id = foreignKeyTable.object_id
INNER JOIN sys.schemas AS foreignKeySchema
ON foreignKeyTable.schema_id = foreignKeySchema.schema_id
INNER JOIN sys.columns AS foreignKeyColumn
ON foreignKeyConstraintColumns.parent_object_id = foreignKeyColumn.object_id
AND foreignKeyConstraintColumns.parent_column_id = foreignKeyColumn.column_id
INNER JOIN sys.tables as referencedTable
ON foreignKeyConstraintColumns.referenced_object_id = referencedTable.object_id
INNER JOIN sys.schemas AS referencedSchema
ON referencedTable.schema_id = referencedSchema.schema_id
INNER JOIN sys.columns AS referencedColumn
ON foreignKeyConstraintColumns.referenced_object_id = referencedColumn.object_id
AND foreignKeyConstraintColumns.referenced_column_id = referencedColumn.column_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment