代码之家  ›  专栏  ›  技术社区  ›  Matt

跨多行拆分可变长度分隔字符串(SQL)

  •  1
  • Matt  · 技术社区  · 16 年前

    我有一个表,其中一列包含一个可变长度的分隔字符串,例如:

    20,0, 5,,^24,0, 0,,^26,0, 0,,^
    281,0, 0,,^34,0, 2,,^48,0, 2,,^44,0, 2,,^20,0, 10,,^
    20,5, 5,,^379,1, 1,,^26,1, 2,,^32,0, 1,,^71,0, 2,,^

    我需要做的是拆分这个字符串,这样^字符后面的每个数字都会返回到新行。比如:



    项目2^24


    项目5^28

    项目7^66
    项目8^39
    项目9^379
    项目10^448

    我尝试过各种分割函数,我可以通过在多个列中对值进行子串处理,然后使用unpivot在多个行中返回值来获得所需的结果,但是这个方法不能处理这个字符串的可变长度。

    有没有更好的办法?

    1 回复  |  直到 16 年前
        1
  •  0
  •   Guffa    16 年前

    首先,让我说这就是为什么你不应该在一个字段中首先有逗号分隔的数据。没有简单有效的方法来处理它。

    也就是说,您可以使用递归查询拆分字符串并从中获取数字:

    with split as
    (
      select
        item = cast('' as varchar(max)),
        source = cast('20,0, 5,,^24,0, 0,,^26,0, 0,,^281,0, 0,,^34,0, 2,,^48,0, 2,,^44,0, 2,,^20,0, 10,,^20,5, 5,,^379,1, 1,,^26,1, 2,,^32,0, 1,,^71,0, 2,,^' as varchar(max))
      union all
      select
        item = substring(source, 1, charindex(',,', source)),
        source = substring(source, charindex(',,', source) + 2, 10000)
      from split
      where source > ''
    )
    select substring(item, 1, charindex(',', item) -1)
    from split
    where item > ''
    

    结果:

    20
    ^24
    ^26
    ^281
    ^34
    ^48
    ^44
    ^20
    ^20
    ^379
    ^26
    ^32
    ^71