How to split a comma-separated value to columns

后端 未结 30 4639
刺人心
刺人心 2020-11-21 04:38

I have a table like this

Value   String
-------------------
1       Cleo, Smith

I want to separate the comma delimited string into two colu

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 05:08

    xml base answer is simple and clean

    refer this

    DECLARE @S varchar(max),
            @Split char(1),
            @X xml
    
    SELECT @S = 'ab,cd,ef,gh,ij',
           @Split = ','
    
    SELECT @X = CONVERT(xml,'  ' +
    REPLACE(@S,@Split,' ') + '    ')
    
    SELECT  T.c.value('.','varchar(20)'),              --retrieve ALL values at once
      T.c.value('(/root/myvalue)[1]','VARCHAR(20)')  , --retrieve index 1 only, which is the 'ab'
      T.c.value('(/root/myvalue)[2]','VARCHAR(20)')
     FROM @X.nodes('/root/myvalue') T(c)
    

提交回复
热议问题