您可以使用以下JOINS
和PARTITION BY
實現這一目標,
SELECT
PKTableOwner, PKTableName, PKColumnName, FKTableOwner, FKTableName, FKColumnName,
(
CASE
WHEN [Count] > 1
THEN '1 to Many'
ELSE '1 to 1'
END
) AS RelationshipType
FROM (
SELECT
CONVERT(SYSNAME, SCHEMA_NAME(OP.SCHEMA_ID)) AS PKTableOwner,
CONVERT(SYSNAME, OP.NAME) AS PKTableName,
CONVERT(SYSNAME, CP.NAME) AS PKColumnName,
CONVERT(SYSNAME, SCHEMA_NAME(OFK.SCHEMA_ID)) AS FKTableOwner,
CONVERT(SYSNAME, OFK.NAME) AS FKTableName,
CONVERT(SYSNAME, CFK.NAME) AS FKColumnName,
COUNT(*) OVER (PARTITION BY OP.SCHEMA_ID, OP.NAME, CP.NAME) AS [Count]
FROM
SYS.FOREIGN_KEYS F
INNER JOIN
SYS.FOREIGN_KEY_COLUMNS FC
ON
F.OBJECT_ID = FC.CONSTRAINT_OBJECT_ID
INNER JOIN
SYS.OBJECTS OP
ON
OP.OBJECT_ID = F.REFERENCED_OBJECT_ID
INNER JOIN
SYS.COLUMNS CP
ON
CP.OBJECT_ID = F.REFERENCED_OBJECT_ID
AND
CP.COLUMN_ID = FC.REFERENCED_COLUMN_ID
INNER JOIN
SYS.OBJECTS OFK
ON
OFK.OBJECT_ID = F.PARENT_OBJECT_ID
INNER JOIN
SYS.COLUMNS CFK
ON
CFK.OBJECT_ID = F.PARENT_OBJECT_ID
AND
CFK.COLUMN_ID = FC.PARENT_COLUMN_ID) F
你的意思是一對一個表和一個一對多表? – Aruna