我有一个包含30个表的数据库。
我希望看到每个表与该数据库之间的关系。
我不知道如何获取所有数据库表关系。
答案 0 :(得分:1)
您可以从INFORMATION_SCHEMA
表中获取约束信息。以下脚本将为您提供主键和外键和表的列表。
WITH PrimaryTable
AS (
SELECT i1.TABLE_NAME
,i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
)
SELECT PK.TABLE_NAME AS PK_Table
,PT.COLUMN_NAME AS PK_Column
,FK.TABLE_NAME AS FK_Table
,CU.COLUMN_NAME AS FK_Column
,C.CONSTRAINT_NAME AS Constraint_Name
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN PrimaryTable AS PT
ON PT.TABLE_NAME = PK.TABLE_NAME