RSS

Get your Foreign Keys

05 Apr

How do you query your ms sql database and find out what columns in your table are foreign keys?

SELECT C.TABLE_CATALOG [PKTABLE_QUALIFIER],

C.TABLE_SCHEMA [PKTABLE_OWNER],

C.TABLE_NAME [PKTABLE_NAME],

KCU.COLUMN_NAME [PKCOLUMN_NAME],

C2.TABLE_CATALOG [FKTABLE_QUALIFIER],

C2.TABLE_SCHEMA [FKTABLE_OWNER],

C2.TABLE_NAME [FKTABLE_NAME],

KCU2.COLUMN_NAME [FKCOLUMN_NAME],

RC.UPDATE_RULE,

RC.DELETE_RULE,

C.CONSTRAINT_NAME [FK_NAME],

C2.CONSTRAINT_NAME [PK_NAME],

CAST(7 AS SMALLINT) [DEFERRABILITY]

FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS C

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU

ON C.CONSTRAINT_SCHEMA = KCU.CONSTRAINT_SCHEMA

AND C.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME

INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC

ON C.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA

AND C.CONSTRAINT_NAME = RC.CONSTRAINT_NAME

INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C2

ON RC.UNIQUE_CONSTRAINT_SCHEMA = C2.CONSTRAINT_SCHEMA

AND RC.UNIQUE_CONSTRAINT_NAME = C2.CONSTRAINT_NAME

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2

ON C2.CONSTRAINT_SCHEMA = KCU2.CONSTRAINT_SCHEMA

AND C2.CONSTRAINT_NAME = KCU2.CONSTRAINT_NAME

AND KCU.ORDINAL_POSITION = KCU2.ORDINAL_POSITION

WHERE  C.CONSTRAINT_TYPE = 'FOREIGN KEY'

and

C.TABLE_NAME ='TimeSpan'
Advertisements
 
Leave a comment

Posted by on April 5, 2011 in SQL

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: