SQL Server CTE查询产生意外结果

时间:2013-07-16 08:56:21

标签: sql sql-server sql-server-2012

我有这样的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)。该查询将第一个PartNum'10050857'复制46个记录(6+(6 + 10 + 24)),它应该只复制6次,第二个PartNum'10050886'复制10个记录,最终部分为'10050923'按预期记录24条记录。

为什么查询通过累积第一条记录后的记录来复制第一条记录?

1 个答案:

答案 0 :(得分: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!