【问题标题】:How can we know PK and FK relation if we have 200 tables in a database of SQL Server. Is there any query to check it [duplicate]如果我们在 SQL Server 的数据库中有 200 个表,我们如何知道 PK 和 FK 关系。是否有任何查询可以检查它[重复]
【发布时间】:2022-02-05 10:53:04
【问题描述】:

除了数据库架构图,还有什么办法可以得到所有具有PK/FK关系的表的列表?

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    最简单的方法是检查系统目录视图 - 试试这个:

    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 了解更多详细信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 2015-11-04
      • 2014-01-30
      • 1970-01-01
      相关资源
      最近更新 更多