T-SQL: Separate String Into Multiple Columns

前端 未结 4 567
刺人心
刺人心 2020-12-21 20:34

Ex.

Column 1:
| word1 word2 word3 word4 |

to

 Col 1:  Col 2:  Col 3:  Col 4:
| word1 | word2 | word3 | word |
4条回答
  •  鱼传尺愫
    2020-12-21 21:11

    With the help of a CROSS APPLY and some XML. Easy to expand and/or contract

    Declare @YourTable table (id int,Column1 varchar(max))
    Insert Into @YourTable values
    (1,'word1 word2 word3 word4'),
    (2,'some other words')
    
    Select A.ID
          ,B.*
     From  @YourTable A
     Cross Apply (
            Select Pos1 = xDim.value('/x[1]','varchar(max)')
                  ,Pos2 = xDim.value('/x[2]','varchar(max)')
                  ,Pos3 = xDim.value('/x[3]','varchar(max)')
                  ,Pos4 = xDim.value('/x[4]','varchar(max)')
                  ,Pos5 = xDim.value('/x[5]','varchar(max)')
                  ,Pos6 = xDim.value('/x[6]','varchar(max)')
                  ,Pos7 = xDim.value('/x[7]','varchar(max)')
                  ,Pos8 = xDim.value('/x[8]','varchar(max)')
                  ,Pos9 = xDim.value('/x[9]','varchar(max)')
             From (Select Cast('' + Replace(A.Column1,' ','')+'' as XML) as xDim) A
           ) B
    

    Returns

提交回复
热议问题