Search code examples
sqlsql-serverfunctiont-sqlleading-zero

Removing Leading Zeros Part 2


SQL Server 2012

I have 3 columns in my table that will be using a function. '[usr].[Udf_OverPunch]'. and substring.

Here is my code:

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

This function works appropriately for what I need it to do. It is basically converting symbols or letters to a designated number based on a data dictionary.

The problem I am having is that there are leading zeros. I just asked a questions about leading zeroes but it won't allow me to do it with the function columns because of the symbols cannot be converted to int.

This is what I am using to get rid of leading zeros (but leave one zero) in my code for the other columns:

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

This works well at turning a value of '000000' to just one '0' or a value of '000060' to '60' but will not work with the function because of the symbol or letter (when trying to convert to int).

As I mentioned, I have 3 columns which produce values that look something like this when the function is not being used:

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

My goal here is to use the function while also removing the leading zeros (unless they are all zeros then keep one zero).

This is what I attempted that isn't working because the value contains a character that isn't an integer:

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

Please let me know if you have any ideas or need more information. :)


Solution

  • 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
    

    or

    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