2016-02-12 82 views
0

SQL查詢看起來是這樣的: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 

任何幫助,將不勝感激。

回答

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() 
0

爲此,您需要一個字符串分隔符。這裏是Jeff Moden的DelimitedSplit8k

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

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

SELECT STUFF((
    SELECT ' ' + Item 
    FROM dbo.DelimitedSplit8K(@Values, ',') 
    WHERE ItemNumber BETWEEN @From AND @To 
    FOR XML PATH('') 
), 1, 1, '') 
+0

這是工作。而且我怎樣才能得到在逗號分隔列表中的值的數量。 –

+0

'SELECT DATALENGTH(@Values)/ 2 - DATALENGTH(REPLACE(@Values,',',''))/ 2' –

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)