Know relationships between all the tables of database in SQL Server

前端 未结 7 2026
灰色年华
灰色年华 2020-11-28 05:00

I wish to all know how the tables in my database are related to each other (i.e PK/FK/UK) and hence i created a database diagram of all my tables in SQL Server. The diagram

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 05:26

    My solution is based on @marc_s solution, i just concatenated columns in cases that a constraint is based on more than one column:

    SELECT
       FK.[name] AS ForeignKeyConstraintName
      ,SCHEMA_NAME(FT.schema_id) + '.' + FT.[name] AS ForeignTable
      ,STUFF(ForeignColumns.ForeignColumns, 1, 2, '') AS ForeignColumns
      ,SCHEMA_NAME(RT.schema_id) + '.' + RT.[name] AS ReferencedTable
      ,STUFF(ReferencedColumns.ReferencedColumns, 1, 2, '') AS ReferencedColumns
    FROM
      sys.foreign_keys FK
      INNER JOIN sys.tables FT
      ON FT.object_id = FK.parent_object_id
      INNER JOIN sys.tables RT
      ON RT.object_id = FK.referenced_object_id
      CROSS APPLY
      (
        SELECT
          ', ' + iFC.[name] AS [text()]
        FROM
          sys.foreign_key_columns iFKC
          INNER JOIN sys.columns iFC
          ON iFC.object_id = iFKC.parent_object_id
            AND iFC.column_id = iFKC.parent_column_id
        WHERE
          iFKC.constraint_object_id = FK.object_id
        ORDER BY
          iFC.[name]
        FOR XML PATH('')
      ) ForeignColumns (ForeignColumns)
      CROSS APPLY
      (
        SELECT
          ', ' + iRC.[name]AS [text()]
        FROM
          sys.foreign_key_columns iFKC
          INNER JOIN sys.columns iRC
          ON iRC.object_id = iFKC.referenced_object_id
            AND iRC.column_id = iFKC.referenced_column_id
        WHERE
          iFKC.constraint_object_id = FK.object_id
        ORDER BY
          iRC.[name]
        FOR XML PATH('')
      ) ReferencedColumns (ReferencedColumns)
    

提交回复
热议问题