2016-11-20 85 views
0

是否有任何方法列出所有外鍵及其關係類型(1對1或1對多)在SQL Server中的分貝?我知道EXEC sp_fkeys存儲過程,但它不顯示外鍵的關係類型。SQL Server:使用一對一和一對多關係獲取所有外鍵

編輯: 我也嘗試了下面的方法,我相信我可以修改它,我也可以理解關係類型,所以任何建議,將不勝感激。

SELECT * 
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC 
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KF ON RC.CONSTRAINT_NAME =   KF.CONSTRAINT_NAME 
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KP ON RC.UNIQUE_CONSTRAINT_NAME = KP.CONSTRAINT_NAME 
+0

你的意思是一對一個表和一個一對多表? – Aruna

回答

0

您可以使用以下JOINSPARTITION 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