【发布时间】:2022-02-05 10:53:04
【问题描述】:
除了数据库架构图,还有什么办法可以得到所有具有PK/FK关系的表的列表?
【问题讨论】:
标签: sql sql-server
除了数据库架构图,还有什么办法可以得到所有具有PK/FK关系的表的列表?
【问题讨论】:
标签: sql sql-server
最简单的方法是检查系统目录视图 - 试试这个:
SELECT
BaseTable = t.name,
ForeignKeyConstraint = fk.name,
ReferencedTable = ref.name
FROM
sys.tables t
INNER JOIN
sys.foreign_keys fk ON fk.parent_object_id = t.object_id
INNER JOIN
sys.tables ref ON fk.referenced_object_id = ref.object_id
这将列出“基本”表、外键约束的名称和引用的表 - 这里来自 AdventureWorks 示例数据库:
| BaseTable | ForeignKeyConstraint | ReferencedTable |
|---|---|---|
| SalesTerritoryHistory | FK_SalesTerritoryHistory_SalesPerson_BusinessEntityID | SalesPerson |
| Store | FK_Store_SalesPerson_SalesPersonID | SalesPerson |
| SalesOrderHeader | FK_SalesOrderHeader_SalesPerson_SalesPersonID | SalesPerson |
| SalesPersonQuotaHistory | FK_SalesPersonQuotaHistory_SalesPerson_BusinessEntityID | SalesPerson |
| ProductModelIllustration | FK_ProductModelIllustration_Illustration_IllustrationID | Illustration |
| WorkOrderRouting | FK_WorkOrderRouting_Location_LocationID | Location |
| ProductInventory | FK_ProductInventory_Location_LocationID | Location |
(等等)
您可以通过进一步检查这些外键约束中涉及的列来扩展此功能 - 查看official MS documentation on system catalog views 了解更多详细信息
【讨论】: