How do you list all tables and their foreign + primary keys in a SQL query? [closed]

StackOverflow https://stackoverflow.com/questions/23612664

  •  20-07-2023
  •  | 
  •  

Question

USE Database
GO

SELECT * FROM sys.tables 
WHERE type = 'PK' AND parent_object_id = OBJECT_ID ('sys.tables')
GO

Any thoughts?

Était-ce utile?

La solution

Is this what you're looking for?

SELECT
    TableName = t.Name,
    IndexName = I.Name,
    FKName = fk.Name,
    ReferencedTable = refT.Name
FROM 
    sys.tables t
LEFT OUTER JOIN 
    sys.indexes i ON i.object_id = t.object_id AND i.is_primary_key = 1
LEFT OUTER JOIN 
    sys.foreign_keys fk ON fk.parent_object_id = t.object_id
LEFT OUTER JOIN 
    sys.tables refT ON fk.referenced_object_id = refT.object_id
ORDER BY
    t.Name, i.Name

Lists all the tables and the primary key index (if present) and any foreign keys (and what other table that FK references)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top