用于第n次循环迭代的SQL逗号分割函数

时间:2016-06-11 17:06:09

标签: sql sql-server sql-server-2008

我有一个动态整数变量,其中计数值是动态加载的。

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.

我们如何通过SQL中的第n个变量实现拆分功能?

2 个答案:

答案 0 :(得分:4)

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 

答案 1 :(得分:3)

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

;WITH cte AS (
SELECT 1 as i
UNION ALL
SELECT i+1
FROM cte
WHERE i < @iCount
)

SELECT @iCountRef = STUFF((
SELECT ',' + CAST(i as nvarchar(10))
FROM cte
FOR XML PATH('')),1,1,'')

SELECT @iCountRef

3的输出:

1,2,3

1的输出:

1

10的输出:

1,2,3,4,5,6,7,8,9,10