2017-07-16 74 views
0

請幫助我瞭解如何讓所有家長參與提交。如果我通過submissionId表(黑色高亮顯示),我應該得到所有家長對於提交(以紅色突出顯示)根據提交的SQL Server獲取所有父母

enter image description here

的樣本數據:

5EAB0B3D-5A17-43A9-9BC2-21B950F4B4E7 24A6DB20-20D1-4063-9DC6-CC1990B26FD7 
4DEA6377-DF7C-415E-8E06-7DDEB34B53F6 45D6A438-61C7-488C-BC83-8AAB491B037D 
9B83B4D0-E122-462F-842D-9A0A4774A6D5 24A6DB20-20D1-4063-9DC6-CC1990B26FD7 
0BED1600-3120-4C3A-BA86-A3BFAC5765FA 9B83B4D0-E122-462F-842D-9A0A4774A6D5 
DB5DF89E-0E6B-46FE-BE9A-CA6F47F4B544 24A6DB20-20D1-4063-9DC6-CC1990B26FD7 

查詢:

WITH n([submissionid], [parentid]) AS 
(
    SELECT 
     [submissionid], 
     [parentid] 
    FROM 
     [submissionrenewal] 
    WHERE 
     [submissionid] = '0BED1600-3120-4C3A-BA86-A3BFAC5765FA' 

    UNION ALL 

    SELECT 
     m.[submissionid], 
     m.[parentid] 
    FROM 
     [submissionrenewal] AS m, 
     n 
    WHERE 
     n.[submissionid] = m.[parentid] 
) 
SELECT DISTINCT * 
FROM n 

輸入

0BED1600-3120-4C3A-BA86-A3BFAC5765FA 

輸出

9B83B4D0-E122-462F-842D-9A0A4774A6D5 
24A6DB20-20D1-4063-9DC6-CC1990B26FD7 
+1

後的樣本數據爲文本..從未發佈樣本數據沒有人可以使用它測試代碼.. –

+0

發佈,數據讓我知道是否有辦法我可以附加它 –

+0

它足夠的還添加樣本數據的預期結果..聽說過'在SQL Server中的遞歸CTE? –

回答

2

你只需要改變連接條件。來自定位查詢的Parentid應與submissionid遞歸部分連接。你必須到剛剛在where條款交換別名m.[submissionid] = n.[parentid]

WITH n([submissionid], [parentid]) -- giving a meaningful CTE name will improve the code readability 
    AS (SELECT [submissionid], 
       [parentid] 
     FROM [submissionrenewal] 
     WHERE [submissionid] = '0BED1600-3120-4C3A-BA86-A3BFAC5765FA' 
     UNION ALL 
     SELECT m.[submissionid], 
       m.[parentid] 
     FROM [submissionrenewal] AS m 
       INNER JOIN n 
         ON m.[submissionid] = n.[parentid]) --here 
SELECT * 
FROM n 

注:始終使用INNER JOIN語法,而不是舊式逗號分隔加入

+0

感謝您的幫助 –

相關問題