代码之家  ›  专栏  ›  技术社区  ›  Jeff Meatball Yang

在SQL中分析多个筛选器

  •  0
  • Jeff Meatball Yang  · 技术社区  · 16 年前

    declare @S varchar(100)
    set @S = '4=2,24=1534'
    

    问题是:

        select 
            cast(idx as varchar(100)) 'idx'
        ,   value 
        ,   SUBSTRING(value, 1, charindex(value, '=')+1)  'first'
        ,   SUBSTRING(value, charindex(value, '=')+1, LEN(value)-charindex(value, '=')-1) 'second'
        from Common.SplitToTable(@S, ',') -- returns (idx int, value varchar(max))
        where len(value) > 0
    

    但我得到的结果是:

    idx    value       first    second
    0      4=2         4        4=
    1      24=1534     2        24=153
    

    idx    value       first    second
    0      4=2         4        2
    1      24=1534     2        1534
    

    救命啊?

    1 回复  |  直到 16 年前
        1
  •  1
  •   user121301 user121301    16 年前

    charindex的参数是向后的(首先是要查找的字符串),并相应地调整长度:

    select 
        cast(idx as varchar(100)) 'idx'
        ,   value 
        ,   SUBSTRING(value, 1, charindex('=', value)-1)  'first'
        ,   SUBSTRING(value, charindex('=', value)+1, LEN(value)-charindex('=',value)) 'second'
        from Common.SplitToTable(@S, ',') -- returns (idx int, value varchar(max))
        where len(value) > 0