要求截取已知分隔符前面字符串例如空格,前面字符串的长度不定,感谢

解决方案 »

  1.   

    select left(col , charindex(' ' , col) - 1) from tb where charindex(' ' , col) > 0
      

  2.   

    substring和charindex结合着做请楼主给出例子
      

  3.   

    create table tb(col varchar(20))
    insert into tb values('112 lll')
    insert into tb values('112115 lll')
    insert into tb values('112224 lll')
    insert into tb values('11234d lll')
    goselect left(col , charindex(' ' , col) - 1) from tb where charindex(' ' , col) > 0drop table tb/*
                         
    -------------------- 
    112
    112115
    112224
    11234d(所影响的行数为 4 行)
    */
      

  4.   

    select substring('需要的##截断后面的',1,charindex('##','需要的##截断后面的')-1)
      

  5.   

    select substring('需要的##截断后面的',1,charindex('##','需要的##截断后面的')-1)
    /*
    需要的
    */
      

  6.   


    if object_id('[tb]') is not null drop table [tb]
    create table [tb](id int identity(1,1),[a] varchar(200))
    go
    insert [tb](a)
    select 'aaaa  bbbb cccc        dddd'
    insert  [tb](a)
    select 'eeeeee  ffff hhhh        yyyy'
    select 
      id,B.A2
    from (
      select id,convert(xml,'<root><row>'+replace(replace(rtrim(ltrim(a)),' ','</row><row>'),'<row></row>','')+'</row></root>') AS A1
      from [tb]
       ) a  outer apply (select a2=T.C.value('.','nvarchar(100)') from a.a1.nodes('/root/row')T(C)) B         id A2
    ----------- -----------------
              1 aaaa
              1 bbbb
              1 cccc
              1 dddd
              2 eeeeee
              2 ffff
              2 hhhh
              2 yyyy(8 行受影响)