-
Website
http://www.tech-recipes.com/ -
Original page
http://www.tech-recipes.com/rx/3194/microsoft-sql-server-how-to-find-the-foreign-keys-in-a-database/ -
Subscribe
All Comments -
Community
-
Top Commenters
-
davak
83 comments · 1 points
-
danishbacker
9 comments · 1 points
-
flexinfo
11 comments · 1 points
-
bej
4 comments · 1 points
-
dimithri
5 comments · 1 points
-
-
Popular Threads
-
Windows 7: How to Prevent the Mouse from Waking your PC
13 hours ago · 1 comment
-
Outlook 2010: Turn Off Attachment Preview
1 week ago · 1 comment
-
Gmail: How to Send SMS Messages Without Using Email
2 weeks ago · 2 comments
-
Windows 7 – Prevent Live Messenger from Opening at Start Up
1 week ago · 1 comment
-
Symfony: Drop Down List Box Without Submit Button
3 weeks ago · 1 comment
-
Windows 7: How to Prevent the Mouse from Waking your PC
Your sql seems to have problems with foreign keys consisting of several columns. I get for example:
IE_FK_ADDRESS_USER IE_ADDRESS INST_ID IE_USER HOLDER_ID
IE_FK_ADDRESS_USER IE_ADDRESS INST_ID IE_USER INST_ID
IE_FK_ADDRESS_USER IE_ADDRESS USER_HOLDER_ID IE_USER HOLDER_ID
IE_FK_ADDRESS_USER IE_ADDRESS USER_HOLDER_ID IE_USER INST_ID
but just the second and third row are okay. I am far from being an sql expert, but the following select returns the correct result for my database:
SELECT
ConstraintName = a.CONSTRAINT_NAME,
FromTable = c.TABLE_NAME,
FromColumn = c.COLUMN_NAME,
ToTable = d.TABLE_NAME,
ToColumn = d.COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS a,
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS b,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE d
WHERE a.CONSTRAINT_TYPE = 'FOREIGN KEY'
and a.CONSTRAINT_NAME = b.CONSTRAINT_NAME
and a.CONSTRAINT_NAME = c.CONSTRAINT_NAME
and b.UNIQUE_CONSTRAINT_NAME = d.CONSTRAINT_NAME
and c.ORDINAL_POSITION = d.ORDINAL_POSITION
ORDER BY a.CONSTRAINT_NAME, c.ORDINAL_POSITION
Best regards,
Heiner