2013-07-16 82 views
3

我有一個CTE這樣的:的SQL Server CTE查詢產生意外結果

WITH CTE(PartNum, RowIndex) AS 
(
     -- Anchor Member 
     SELECT 
      PartNum 
      ,CAST(OurQty AS INT) AS RowIndex 
     FROM dbo.RcvDtl 
     WHERE OurQty > 0 
     UNION ALL 
     -- Recursive Member 
     SELECT 
      PartNum 
      ,RowIndex - 1 
     FROM CTE 
     WHERE RowIndex - 1 > 0 
) 
SELECT 
    tbl1.PONum, tbl1.PartNum, 
    CAST(tbl1.OurQty AS INT) AS Quantity, 
    tbl2.RowIndex AS RowIndex 
FROM 
    dbo.RcvDtl AS Tbl1 
INNER JOIN 
    CTE AS Tbl2 ON Tbl1.PartNum = Tbl2.PartNum 
WHERE 
    tbl1.PONum = '63' 
ORDER BY 
    Tbl1.PartNum OPTION(MAXRECURSION 1000) 

以下哪個表上運行:

| PartNum | Quantity 
--------------------- 
    10050857 6 
    10050886 10 
    10050923 24 

查詢的想法是複製的記錄(PartNum )根據其數量。當查詢應該重複6次時,第二部分數字「10050886」由10條記錄按預期方式複製第一部分數字「10050857」(46+記錄(6 + 10 + 24)),最後一部分數字「10050923」按預期的24記錄。

爲什麼查詢通過第一條記錄之後的記錄累積來複制第一條記錄?

+0

它的外觀和工作正常 - http://sqlfiddle.com/#!6/0b685/2 –

+0

雖然我已經改變了一些列名稱,使其運行。所以你可能在某個地方使用了錯誤的列,這會導致錯誤的連接和結果。請仔細檢查您的列名(數量<> OurQty?) –

+0

當我在Microsoft SQL Server Management Studio 2012上運行它時,它返回80條記錄 – samb90

回答

1

我不得不更改名稱一點點,但你的CTE做的工作:

WITH CTE(PartNum, RowIndex) AS 
(
     -- Anchor Member 
     SELECT 
      PartNum 
      ,CAST(OurQty AS INT) AS RowIndex 
     FROM dbo.RcvDtl 
     WHERE OurQty > 0 
     UNION ALL 
     -- Recursive Member 
     SELECT 
      PartNum 
      ,RowIndex - 1 
     FROM CTE 
     WHERE RowIndex - 1 > 0 
) 
SELECT CTE.PartNum, dbo.RcvDtl.OurQty, CTE.RowIndex from CTE INNER JOIN dbo.RcvDtl 
ON CTE.PartNum = dbo.RcvDtl.PartNum 
order by PartNum,RowIndex 

只需再次檢查你的代碼,它會工作。好戲也是,我喜歡CTE!