如何在下划线上拆分列

时间:2019-04-23 13:40:46

标签: sql-server tsql split

****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

客户ID是其中的原始列,我需要根据下划线将多个字段划分为 customerID1 customerID2 customerID3 customerID4

enter image description here

1 个答案:

答案 0 :(得分:2)

由于最多只能有4个ID,因此可以使用parsename()。但是,我会选择XML方法。

示例

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 

返回

enter image description here