0
****Original          Column    After separated****
CustomerID  CustomerID1 CustomerID2 CustomerID3 CustomerID4
1_2_R_0           1             2           R      0
3_3_0             3             3           0    
4_2               4             2

Customer ID is the original column from this I need to split into multiple column base on the underscore to customerID1, customerID2, customerID3 and customerID4.

enter image description here

Maqbul
  • 11
  • 1

1 Answers1

2

Since there is a max of only 4 IDs, you could use parsename(). However, I would opt for the XML approach.

Example

Select A.CustomerID
      ,B.*
 From  YourTable A
 Cross Apply (
    Select CustomerID1 = xDim.value('/x[1]','varchar(100)')
          ,CustomerID2 = xDim.value('/x[2]','varchar(100)')
          ,CustomerID3 = xDim.value('/x[3]','varchar(100)')
          ,CustomerID4 = xDim.value('/x[4]','varchar(100)')
     From  (values (cast('<x>' + replace([CustomerID],'_','</x><x>')+'</x>' as xml))) X(xDim)
 ) B 

Returns

enter image description here

John Cappelletti
  • 79,615
  • 7
  • 44
  • 66