SQL Server:基于偏移值的逗号分隔列表

时间:2016-02-12 04:30:15

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

SQL查询如下所示:

Declare @Values nvarchar(max) , @From int , @To int
Set @Values = 'a,b,c,d,e,f,g,h,i,j'
Set @From = 3 , @To = 7

必须根据@From@To将值拆分为多行。根据以上查询,所需的输出是

 c d e f g

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

你需要一个字符串拆分器。以下是Jeff Moden的DelimitedSplit8k

strval

答案 1 :(得分:0)

您可以使用此查询:

declare @Values nvarchar(max) 
      , @From int 
      , @To int

set @Values = 'a,b,c,d,e,f,g,h,i,j'
set @From = 3
set @To = 7

;with cte as(
select substring(@Values, charindex(',', @Values, 1) + 1, 4000) as st
     , substring(@Values, 1, charindex(',', @Values, 1) - 1) ch
     , 1 as rn
union all
select substring(st, t + 1, 4000) as st
     , substring(st, 1, t - 1) ch
     , rn + 1 as rn
  from cte
    cross apply (select case when charindex(',', st, 1) = 0 then 8000 else charindex(',', st, 1) end) t(t)
  where rn < @To
    and datalength(st) > 0)

select stuff((
select ' ' + ch as 'text()'
  from cte
  where rn between @From and @To
  order by rn
  for xml path('')), 1, 1, '')
  option (maxrecursion 0)

答案 2 :(得分:0)

免责声明:我是该项目的所有者Eval SQL.NET

如果您有C#背景,您可能会考虑使用这个库直接在T-SQL中使用C#语法

DECLARE @Values NVARCHAR(MAX) ,
    @From INT ,
    @To INT

SELECT  @Values = 'a,b,c,d,e,f,g,h,i,j' ,
        @From = 3 ,
        @To = 7

-- The index start at 0 and not at 1 in C#
DECLARE @sqlnet SQLNET = SQLNET::New('
values.Split('','').Skip(from - 1).Take(to - from + 1)')
.ValueString('values', @Values)
.Val('from', @From)
.Val('to', @to)

-- In multiple rows
SELECT  *
FROM    [dbo].[SQLNET_EvalTVF_1](@sqlnet)

-- In same rows
SELECT  SQLNET::New('
var splits = values.Split('','').Skip(from - 1).Take(to - from + 1).ToList();
return string.Join('' '',  splits);')
.ValueString('values', @Values)
.Val('from', @From)
.Val('to', @to)
.Eval()