Where are my foreign keys?!?!?!??!

If you would ever, from whatever reason, need to check/validate/list foreign keys in the MS SQL 2000/2005 database, here is the magical query you won't find on msdn:

SELECT sysforeignkeys.constid, sysforeignkeys.fkeyid,
sysforeignkeys.rkeyid, sysobjects.name as keyname,
soFK.name AS firsttable, soRK.name as secondtable
FROM sysforeignkeys
LEFT OUTER JOIN sysobjects soKey ON sysforeignkeys.constid = soKey.id
LEFT OUTER JOIN sysobjects soFK ON sysforeignkeys.fkeyid = soFK.id
LEFT OUTER JOIN sysobjects soRK ON sysforeignkeys.rkeyid = soRK.id

Column names (linked columns) are not included in query - I didn't need it for my purpose, but you can include them of course. :D


This blog post has moved to a new address. If you would like to leave a comment, please do it there.

Published Tuesday, August 15, 2006 5:33 PM by Adis Jugo
Filed under: ,