Monday, August 27, 2012

Query to get the List of all Foreign Keys in a database




Please change the name of the database and run it.

USE "database name"
go

SELECT
      OBJECT_NAME(constraint_object_id) FOREIGN_KEY_NAME,
      OBJECT_NAME(parent_object_id)     TABLE_NAME,
      (SELECT name FROM sys.columns WHERE object_id = parent_object_id AND column_id = parent_column_id) COLUMN_NAME,
      OBJECT_NAME(referenced_object_id) REFERENCED_TABLE_NAME,
      (SELECT name FROM sys.columns WHERE object_id = referenced_object_id AND referenced_column_id = column_id) REFERENCED_COLUMN_NAME
FROM sys.foreign_key_columns
ORDER BY REFERENCED_TABLE_NAME
go



No comments:

Post a Comment