CTE error: "Types don't match between the anchor and the recursive part"

Viewed 86534

I am executing the following statement:

;WITH cte AS (
  SELECT 
    1 as rn, 
    'name1' as nm
  UNION ALL
  SELECT 
    rn + 1,
    nm = 'name' + CAST((rn + 1) as varchar(255))
  FROM cte a WHERE rn < 10)
SELECT * 
FROM cte

...which finishes with the error...

Msg 240, Level 16, State 1, Line 2
Types don't match between the anchor and the recursive part in column "nm" of recursive query "cte".

Where am I making the mistake?

9 Answers

In my case, I messed up the sequence of columns in top and bottom clauses of UNION ALL. And it turned out that a varchar column appeared 'under' an int one. An easy mistake to make of you have lots of columns

If you use CONCAT in the recursive term of a rcte, since the output type of concat is varchar(MAX), you only need to cast the column in the initial query:

WITH rcte AS (
    SELECT 1 AS nr, CAST('1' AS varchar(MAX)) AS trail
    UNION ALL
    SELECT nr+1, CONCAT(trail, '/', nr+1)
    FROM rcte
    WHERE nr < 5
)
SELECT * FROM rcte;

enter image description here

I would recommend using nvarchar(max)

WITH CTE AS (
SELECT x,x_name FROM (VALUES (1,CAST('' AS nvarchar(MAX)))) AS     test(x,x_name)
UNION ALL
SELECT x + 1 x, CONCAT(x_name,x+1)  FROM CTE WHERE x < 10 )
SELECT * FROM CTE
WITH rcte AS (
    SELECT 1 AS nr, CAST('1' AS varchar(MAX)) AS trail
    UNION ALL
    SELECT nr+1, cast(CONCAT(trail, '/', nr+1) as varchar(max))
    FROM rcte
    WHERE nr < 5
)
SELECT * FROM rcte;
Related