Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Comma Split function for nth loop iteration

i have a dynamic integer variable where the count number is loaded dynamically.

iCount = 3 
or iCount = 10  ( dynamically number is loaded ).

I have to split the number as 1,2,3 for the iCount = 3
1,2,3,4,5,6,7,8,9,10 for the iCount = 10
and 1 for the iCount = 1.

How can we achive the split functionality through nth variable in SQL ?

like image 349
goofyui Avatar asked Mar 13 '23 00:03

goofyui


1 Answers

A simpler version

DECLARE @iCount int = 10, @iCountRef varchar(100);


WITH CTE AS (
SELECT 1 as i, CAST('1' AS VARCHAR(8000)) AS S
UNION ALL
SELECT i+1, CAST(CONCAT(S, ',', i+1) AS VARCHAR(8000))
FROM cte
WHERE i < @iCount
)
SELECT @iCountRef =  S
FROM cte
Where i = @iCount;

SELECT @iCountRef 
like image 189
Martin Smith Avatar answered Mar 21 '23 02:03

Martin Smith