删除前导零第 2 部分

Removing Leading Zeros Part 2

SQL 服务器 2012

我的 table 中有 3 列将使用函数。 '[usr].[Udf_OverPunch]'。和子字符串。

这是我的代码:

[usr].[Udf_OverPunch](SUBSTRING(col001, 184, 11)) as REPORTED_GAP_DISCOUNT_PREVIOUS_AMOUNT

这个函数可以很好地满足我的需要。它基本上是根据数据字典将符号或字母转换为指定的数字。

我遇到的问题是有前导零。我刚刚问了一个关于前导零的问题,但它不允许我用函数列来做,因为符号不能转换为 int。

这就是我用来在其他列的代码中去掉前导零(但保留一个零)的方法:

cast(cast(SUBSTRING(col001, 217, 6) as int) as varchar(25)) as PREVIOUS_REPORTING_PERIOD

这在将“000000”的值变成一个“0”或将“000060”的值变成“60”时效果很好,但由于符号或字母的原因(当试图转换为整数)。

正如我所提到的,我有 3 个列在未使用该函数时生成的值看起来像这样:

'0000019753{'
'0000019748G'
'0000019763H'

我的目标是在使用该函数的同时删除前导零(除非它们都是零,然后保留一个零)。

这是我尝试过的方法,但它不起作用,因为该值包含一个非整数字符:

[usr].[Udf_OverPunch]cast(cast(SUBSTRING(col001, 184, 6) as int) as varchar(25)) as REPORTED_GAP_DISCOUNT_PREVIOUS_AMOUNT,

如果您有任何想法或需要更多信息,请告诉我。 :)

select      case when col like '%[^0]%' then substring(col,patindex('%[^0]%',col),len(col)) when col like '%0%' then '0' else col end   

from        tab

select      case when col like '%[^0]%' then right(col,len(ltrim(replace(col,'0',' ')))) when col like '%0%' then '0' else col end

from        tab

我正在使用允许使用正则表达式进行替换的 T-SQL CLR 函数处理此类替换。所以,解决方案将是这样的:

[dbo].[fn_Utils_RegexReplace] ([value], '^0{1,}(?=.)', '')

您需要创建这样的函数,因为 T-SQL(内置)中不支持正则表达式。

例如:

试试这个,

declare @i varchar(50)='0000019753}'--'0000019753'

select case when ISNUMERIC(@i)=1 then 
cast(cast(@i as bigint) as varchar(50)) else @i end

[usr].[Udf_OverPunch]( case when ISNUMERIC(col001)=1 then 
cast(cast(col001 as bigint) as varchar(50)) else col001 end)