2011-06-13 520 views
0

我是CTE的新手,我試圖弄清楚這一點。 我有一個表格,用於存儲所有合同,我擁有最新合同「合同A」的記錄,我希望通過歷史順序回顧相關合同,以找到具有特定標準的最新合同,有時候它會是我已經擁有的合同。有時深一層,也許深達5層。我建了一個CTE,它限制了記錄與「合同A」相關的記錄,但它進入一個無限循環和SQL殺死它BTW,我使用SQL Server 2008的 這裏是代碼我有:通過記錄歷史記錄找回想要的記錄的遞歸查找

CREATE TABLE #t_Contracts 
( ContractOID INT NOT NULL 
, SystemSourceOID SMALLINT NOT NULL 
) 

--"Contract A" 
INSERT #t_Contracts 
SELECT 7463027, 2 


WITH Contract_CTE (ContractOID, SystemSourceOID, PrevContractOID, ProductCodeType,Comment, Contractlevel) 
AS 
(
    --Anchor with "Contract A" 
    SELECT CON.ContractOID, CON.SystemSourceOID, CON.PrevContractOID, PRD.ProductCodeType, PRD.Comment, 0 AS Contractlevel 
    FROM UBASS.dbo.[Contract] AS CON 
    INNER JOIN #t_Contracts   AS TMP ON CON.ContractOID = TMP.ContractOID 
              AND CON.SystemSourceOID = TMP.SystemSourceOID 
    INNER JOIN UBASS.dbo.Product AS PRD ON CON.ProductOID = PRD.ProductOID 
              AND CON.SystemSourceOID = PRD.SystemSourceOID 
    UNION ALL 
    --"Contract A" Previous contracts 
    SELECT CON.ContractOID, CON.SystemSourceOID, CON.PrevContractOID, PRD.ProductCodeType, PRD.Comment, Contractlevel + 1 
    FROM  UBASS.dbo.[Contract] AS CON 
    INNER JOIN Contract_CTE AS pCON ON pCON.PrevContractOID = CON.ContractOID 
       AND CON.SystemSourceOID = pCON.SystemSourceOID 
    INNER JOIN UBASS.dbo.Product AS PRD ON CON.ProductOID = PRD.ProductOID 
              AND CON.SystemSourceOID = PRD.SystemSourceOID 

) 



SELECT * FROM Contract_CTE 
WHERE 
ProductCodeType NOT IN ('MPP','RBP','STP','RCP','BNE') 
AND Comment != 'RETENTION' 

--WHERE ContractOID = 7463027 AND SystemSourceOID = 2 
+0

無限循環已經解決,這是一個數據問題,最古老的契約的PrevContractOID指向一個新的契約,而不是空的。但我現在得到重複的記錄。它不返回3條記錄,而是每條記錄返回6條記錄。 – greektreat 2011-06-13 15:32:38

回答

0

因此,此代碼按預期工作,它是所有數據問題。與它解決它很好!