如何在SQL查询中列出所有表及其外键+主键?

时间:2014-05-12 15:09:24

标签: sql sql-server list

USE Database
GO

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

有什么想法?

1 个答案:

答案 0 :(得分:1)

这是你正在寻找的吗?

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

列出所有表和主键索引(如果存在)和任何外键(以及FK引用的其他表)