在cte query sqlserver 2008中初始化和增加变量

时间:2012-10-01 06:32:22

标签: sql sql-server sql-server-2008 common-table-expression

我正在使用sqlserver 2008,我想在我的第二部分(问题行)中同时初始化和增加变量(@NUMTwo)。

我正在创建一个cte查询。

这是可能的,如果是,请告诉我。

以下是一个示例。我希望我很清楚。

CREATE table #TempTable 
(
childProductID  INT,parentProductID INT,productModel varchar(50),[Num2] VARCHAR(100)
)

DECLARE @NUMTwo  INT = 0
WITH tableR   AS    
 (

        -- First Part
    SELECT childProductID = null,parentProductID=null,productModel  from Products where productid in (@a),[Num2] = convert(varchar(100), '')
            UNION ALL
            --Second Part            
    SELECT e.childProductID,e.parentProductID,prd.productModel FROM ProductIncludes AS e  
            ,[Num2] = convert(varchar(100),'1.'  + @NUMTwo+=1 )    -- Problem line
    INNER JOIN  Products AS PRD ON e.childProductID = PRD.productID      
    WHERE parentProductID in (@a)  

      )

INSERT INTO #TempTable(childProductID,parentProductID,productModel,[Num2])
SELECT childProductID,parentProductID,productModel,[Num2]

END 
SELECT * FROM #TempTable

2 个答案:

答案 0 :(得分:4)

您需要在查询的锚点部分“初始化”一列,然后“递增”递归部分中的列。

这样的东西
DECLARE @NUMTwo  INT = 0
;WITH Test AS (
    SELECT  [Num2] = convert(varchar(MAX), ''),
            @NUMTwo [N] 
    UNION ALL
    SELECT  [Num2] = '1.'  + convert(varchar(MAX),[N]+1),
            [N]+1
    FROM    TEst
    WHERE   [N] < 10
)
SELECT  *
FROM    Test

SQL Fiddle DEMO

答案 1 :(得分:1)

如果参数@NUMTwo仅用于编号行,您可以使用ROW_NUMBER() OVER(...)代替它,如下所示:

WITH tableR   AS    
 (
    SELECT childProductID = NULL, parentProductID = NULL, 
      productModel, NUMTwo = CAST('0' AS VARCHAR(10))
    FROM Products 
    WHERE 
      productid in (@a),
      [Num2] = convert(varchar(100), '')
    UNION ALL          
    SELECT e.childProductID, e.parentProductID, 
      prd.productModel, 
      NUMTwo = '1.' + 
        CAST( ROW_NUMBER() OVER(ORDER BY (SELECT 0)) AS VARCHAR(10))
    FROM ProductIncludes AS e
    INNER JOIN  Products AS PRD ON e.childProductID = PRD.productID      
    WHERE parentProductID in (@a)  
)