sql函数在给出开始和结束编号时获取逗号分隔值

时间:2014-01-22 12:45:23

标签: sql sql-server

假设我的起始编号为5,结束编号为10.我想要一个sql函数,它给我一个字符串逗号分隔值,如(5,6,7,8,9,10)。

提前致谢。

1 个答案:

答案 0 :(得分:0)

使用它:

declare @start int
declare @end int
set @start = 5;
set @end = 10;

;with ranges AS
(
    SELECT 
        @start as val
    UNION ALL
    SELECT 
        val + 1
    FROM   ranges
    WHERE  val+1 <= @end
)
Select distinct 
       substring((select ','+convert(varchar, ranges.val) as [text()]
                  from   ranges
                  order by 
                         ranges.val
                  for XML path ('')),2, 1000)
from   ranges