SQL Server - 需要更正从ABC 1-1-1到ABC 001-001-001的编号模式

时间:2016-12-19 23:08:23

标签: sql-server

因此我们需要在客户编号模式中填充零。破折号之间的数字长度应始终为3.因此,首先它应该找到第一个空格,然后找到破折号之间的数字长度,如果它小于3则应该用零填充

Ex:XYZ 45-678-2

这应该更正为XYZ 045-678-002。

1 个答案:

答案 0 :(得分:0)

> **Edit Updated for new patterns**

Declare @YourTable table (ID int,YourField varchar(50))
Insert Into @YourTable values
(1,'XYZ 45-678-2'),
(2,'XYZ 45-678'),
(3,'DA 1-1'),
(4,'XYZ 123-678-9-234')


--Update @YourTable Set YourField     -- If Satisfied Remove Comment
Select A.*,NewField                   -- If Satisfied Remove This Line
       = Concat(Pos1
              ,Format(Try_Convert(int,Pos2),' 000') 
              ,Format(Try_Convert(int,Pos3),'-000') 
              ,Format(Try_Convert(int,Pos4),'-000') 
              ,Format(Try_Convert(int,Pos5),'-000') 
              ,Format(Try_Convert(int,Pos6),'-000') 
              ,Format(Try_Convert(int,Pos7),'-000') 
              ,Format(Try_Convert(int,Pos8),'-000') 
              ,Format(Try_Convert(int,Pos9),'-000') 
               )
  From  @YourTable A
  Cross Apply (
                Select Pos1 = xDim.value('/x[1]','varchar(50)')
                      ,Pos2 = xDim.value('/x[2]','varchar(50)')
                      ,Pos3 = xDim.value('/x[3]','varchar(50)')
                      ,Pos4 = xDim.value('/x[4]','varchar(50)')
                      ,Pos5 = xDim.value('/x[5]','varchar(50)')
                      ,Pos6 = xDim.value('/x[6]','varchar(50)')
                      ,Pos7 = xDim.value('/x[7]','varchar(50)')
                      ,Pos8 = xDim.value('/x[8]','varchar(50)')
                      ,Pos9 = xDim.value('/x[9]','varchar(50)')
                 From (Select Cast('<x>' + Replace(Replace(YourField,' ','-'),'-','</x><x>')+'</x>' as XML) as xDim) A
              ) B
  Where YourField Like '% %-%'

更新的结果将是

ID  YourField
1   XYZ 045-678-002
2   XYZ 045-678
3   DA 001-001
4   XYZ 123-678-009-234