Find all Foreign Keys in a SQL Server DB


/ Published in: SQL
Save to your folder(s)



Copy this code and paste it in your HTML
  1. SELECT
  2. K_Table = FK.TABLE_NAME,
  3. FK_Column = CU.COLUMN_NAME,
  4. PK_Table = PK.TABLE_NAME,
  5. PK_Column = PT.COLUMN_NAME,
  6. Constraint_Name = C.CONSTRAINT_NAME
  7. FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
  8. INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
  9. INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
  10. INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
  11. INNER JOIN (
  12. SELECT i1.TABLE_NAME, i2.COLUMN_NAME
  13. FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
  14. INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
  15. WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
  16. ) PT ON PT.TABLE_NAME = PK.TABLE_NAME

URL: http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-in-database/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.