Press "Enter" to skip to content

Removing Leading Zeroes from a String in T-SQL

Steve Stedman gets rid of leading zeroes:

When working with data in SQL Server, there may be times when you need to remove leading zeros from a string. This task can be particularly common when dealing with numerical data stored as strings, such as ZIP codes, product codes, or other formatted numbers. In this blog post, we’ll explore several methods to remove leading zeros in SQL Server.

I’m not sure I see the reason to use anything other than CAST() (or, better yet, TRY_CAST()), but Steve does show two other methods.

2 Comments

  1. Louis Davidson
    Louis Davidson 2024-07-12

    Yeah, I thought the example of using PATINDEX probably should have been more complex of a string since starting with

    DECLARE @originalString NVARCHAR(100) = ‘00012345’

    You can just use REPLACE. (But the technique could be used to remove leading ‘A’ characters too for that matter.

    The loop example could be used to remove the first leading zero, or the second, or every other one. Customer’s need weird things at times 🙂

    • Kevin Feasel
      Kevin Feasel 2024-07-12

      Yeah, that’s fair. Early morning me is a little more dogmatic about things than afternoon me, so I agree that you make a good point. Now, something like “remove the third character if and only if it is a 0,” that’s the kind of zany customer demands that make me want to tear out other peoples’ hair (because I want to keep mine).

Comments are closed.