Hi,@mille
Welcome to Microsoft T-SQL Q&A Forum!
First, when you cast the anchor part to varchar(max), it automatically means that the recursive part will also be varchar(max).
The data type of 'Hello world!' is varchar, and the summed length of the two data types, I think is varchar(2). n+1 is still int.
In a recursive CTE, the data types must match exactly, so '1' is varchar(1). If you specify varchar without length in CAST, you get varchar(30), so txt + ', ' + CAST(n+1 AS varchar) is varchar(33).
Taking a look at the example below to help you understand:
;WITH CTE(n, txt) AS
(
SELECT 1, CAST('1' AS varchar(30))
UNION ALL
SELECT
n+1,
CAST(CONCAT(txt, ', ', n+1) AS varchar(30))
FROM
CTE
WHERE
n < 10
)
SELECT *
FROM CTE
Best regards,
Bert Zhou
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.