2014-04-03 54 views
1

粘附值對我有一列中的一個單元的以下的字符串(例如):SQL,得到從逗號分隔的字符串

1,4,3,8,23,7 

我需要得到對值如下到一個新的表:

(1,4) 
    (4,3) 
    (3,8) 
     (8,23) 
     (23,7) 

我希望我解釋什麼,我需要正確的,這樣你能理解我:) 我apprecciate甚至一句話答案,因爲我喜歡解決編程問題我自己:)

回答

2
DECLARE @data varchar(2000) = '1,4,3,8,23,7' 

;WITH x as 
(
    SELECT t.c.value('.', 'VARCHAR(2000)') v, row_number() over (order by (select 1)) rn 
     FROM (
     SELECT x = CAST('<t>' + 
       REPLACE(@data, ',', '</t><t>') + '</t>' AS XML) 
    ) a 
    CROSS APPLY x.nodes('/t') t(c) 
) 
SELECT t1.v, t2.v 
FROM x t1 
JOIN x t2 
on t1.rn = t2.rn - 1 

結果:

1 4 
4 3 
3 8 
8 23 
23 7 
1

抱歉殺風景:)

declare 
    @col_list varchar(1000), 
    @sep char(1) 

set @col_list = '1,4,3,8,23,7' 
set @sep = ',' 

;with x as (
select substring(@col_list, n, charindex(@sep, @col_list + @sep, n) - n) as col, 
row_number() over(order by n) as r 
from numbers where substring(@sep + @col_list, n, 1) = @sep 
and n < len(@col_list) + 1 
) 
select x2.col, x1.col 
from x as x1 
inner join x as x2 on x1.r = x2.r+1 

http://sqlblog.com/blogs/adam_machanic/archive/2006/07/12/you-require-a-numbers-table.aspx

1

不使用XML的另一個解決方案 - 使用遞歸CTE一套明確的基礎的方法。

create table #tmp (value varchar(100)); 
insert into #tmp values ('1,4,3,8,23,7'); 


with r as (
    select value, cast(null as varchar(100)) [x], 0 [no] from #tmp 
    union all 
    select right(value, len(value)-case charindex(',', value) when 0 then len(value) else charindex(',', value) end) [value] 
    , left(r.[value], case charindex(',', r.value) when 0 then len(r.value) else abs(charindex(',', r.[value])-1) end) [x] 
    , [no] + 1 [no] 
    from r where value > '') 

select '(' + cast(s1.[x] as varchar(10)) +', '+ cast(s2.[x] as varchar(10)) + ')' 
from r as s1 
join r as s2 on s1.[no] + 1 = s2.[no] 
where s1.x is not null; 


drop table #tmp; 

輸出:

result 
--------- 
(1, 4) 
(4, 3) 
(3, 8) 
(8, 23) 
(23, 7)