0

How to get the name, referenced schema and table for a all foreign keys in a SQL Sever database?

1 Answer 1

1

Old School

SELECT 
  [ForeignKey] = f.name
, [TableName] = OBJECT_NAME(f.parent_object_id), COL_NAME(fc.parent_object_id,fc.parent_column_id)
, [ReferenceTableName] = OBJECT_NAME (f.referenced_object_id)
, ReferenceColumnName = COL_NAME(fc.referenced_object_id, fc.referenced_column_id)
FROM 
sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id

New School:

From

http://msdn.microsoft.com/en-us/library/aa175805%28SQL.80%29.aspx

SELECT 
      KCU1.CONSTRAINT_SCHEMA as 'CONSTRAINT_SCHEMA_1'
    , KCU1.CONSTRAINT_NAME AS 'FK_CONSTRAINT_NAME'
    , KCU1.TABLE_SCHEMA  as 'TABLE_SCHEMA_1'
    , KCU1.TABLE_NAME AS 'FK_TABLE_NAME'
    , KCU1.COLUMN_NAME AS 'FK_COLUMN_NAME'
    , KCU1.ORDINAL_POSITION AS 'FK_ORDINAL_POSITION'
    , '----------' as Sep1
    , KCU2.CONSTRAINT_NAME AS 'UQ_CONSTRAINT_NAME'
    , KCU2.CONSTRAINT_SCHEMA  as 'CONSTRAINT_SCHEMA_2'
    , KCU1.TABLE_SCHEMA  as 'TABLE_SCHEMA_2'
    , KCU2.TABLE_NAME AS 'UQ_TABLE_NAME'
    , KCU2.COLUMN_NAME AS 'UQ_COLUMN_NAME'
    , KCU2.ORDINAL_POSITION AS 'UQ_ORDINAL_POSITION'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1
ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG 
   AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
   AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2
ON KCU2.CONSTRAINT_CATALOG = 
RC.UNIQUE_CONSTRAINT_CATALOG 
   AND KCU2.CONSTRAINT_SCHEMA = 
RC.UNIQUE_CONSTRAINT_SCHEMA
   AND KCU2.CONSTRAINT_NAME = 
RC.UNIQUE_CONSTRAINT_NAME
   AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION
1
  • I strongly prefer "old school"
    – marc_s
    Dec 6, 2013 at 14:57

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.