Initialize and increment a variable inside cte query sqlserver 2008

I am using sqlserver 2008, I want to initialize and increment the variable ( @NUMTwo) at the same time, in my second part (Problem Line).

I am creating a cte request.

Is this possible, if so, please let me know.

The following is an example of an example. I hope I understand.

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
+5
source share
2 answers

If the parameter is @NUMTwointended for line numbering, you can use it ROW_NUMBER() OVER(...)instead:

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)  
)
+1
source

You need to “Initialize” the column in the acnhor part of the query, and then “oncrement” this column in the recursive parts.

Sort of

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

+3

All Articles