SQL,从逗号分隔的字符串中获取附加的值对

时间:2014-04-03 14:06:05

标签: sql sql-server regex string

我在列的一个单元格中有以下字符串(示例):

 1,4,3,8,23,7

我需要将下面的值对添加到新表中:

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

我希望我能正确解释我的需要,以便你能理解我:) 我甚至赞赏一句话答案,因为我喜欢自己解决编程问题:)

3 个答案:

答案 0 :(得分: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 :(得分: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://dataeducation.com/you-require-a-numbers-table/

答案 2 :(得分: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)