在表中填充nvarchar列的零

时间:2016-12-06 02:48:08

标签: sql padding

我想在点(。)之前仅为单个数字值添加零 当我使用 输入:

1.3.45 TU 3
1.2.5 TU 8

预期产出:

01034503
01020508

当前查询:

select REPLACE(
                replace(
                            replace(@Column,'TU','')   -- remove TU
                        ,'.',''   -- remove dot 
                        )
                ,' ','') -- remove space
from Table;

当前输出:

13453
1258

2 个答案:

答案 0 :(得分:1)

如果是SQL Server,可以使用Split / Parse函数来规范化字符串

Declare @YourTable Table (YourField varchar(25))
Insert Into @YourTable values 
('1.3.45 TU 3'),
('1.2.5 TU 8')

Select A.*
      ,NewField = B.String
 From  @YourTable A
 Cross Apply (
       Select String = ltrim((Select cast(RetVal as varchar(25)) 
         From (Select RetSeq,RetVal=Right('00'+RetVal,2) 
               From   [dbo].[udf-Str-Parse](replace(YourField,' ','.'),'.') 
               Where  Try_Convert(int,RetVal)>=0 ) A
         For XML Path ('')))
       ) B

返回

YourField      NewField
1.3.45 TU 3    01034503
1.2.5 TU 8     01020508

UDF(如果需要)

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From (Select x = Cast('<x>'+ Replace(@String,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A 
    Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')

答案 1 :(得分:0)

零在哪里?你想要这样的东西:

select ('0' +                                       -- initial zero
        replace(replace(replace(@Column, 'TU', ''   -- remove TU
                               ), '.', '0'          -- replace dot with zero 
                        ), ' ', ''
               )                                    -- remove space
       )
from Table;