How to split a comma-separated value to columns

后端 未结 30 3961
刺人心
刺人心 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 04:58

    mytable:

    Value  ColOne
    --------------------
    1      Cleo, Smith
    

    The following should work if there aren't too many columns

    ALTER TABLE mytable ADD ColTwo nvarchar(256);
    UPDATE mytable SET ColTwo = LEFT(ColOne, Charindex(',', ColOne) - 1);
    --'Cleo' = LEFT('Cleo, Smith', Charindex(',', 'Cleo, Smith') - 1)
    UPDATE mytable SET ColTwo = REPLACE(ColOne, ColTwo + ',', '');
    --' Smith' = REPLACE('Cleo, Smith', 'Cleo' + ',')
    UPDATE mytable SET ColOne = REPLACE(ColOne, ',' + ColTwo, ''), ColTwo = LTRIM(ColTwo);
    --'Cleo' = REPLACE('Cleo, Smith', ',' + ' Smith', '') 
    

    Result:

    Value  ColOne ColTwo
    --------------------
    1      Cleo   Smith
    

提交回复
热议问题