110

I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple VARCHAR(10) field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'.

Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an RTRIM function, but this seems only to remove spaces.

Abdul Rasheed
  • 6,486
  • 4
  • 32
  • 48
Tim C
  • 70,053
  • 14
  • 74
  • 93
  • 3
    As a upvote to David Walker's http://stackoverflow.com/a/11129399/1635441 response, please refer to Arvo's answer posted: http://stackoverflow.com/a/662437/1635441 – ramizmoh Jan 31 '13 at 12:43

15 Answers15

167
select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
Ian Horwill
  • 2,957
  • 2
  • 24
  • 24
  • 9
    This will have problems when the string is entirely made up of "0", since it will never match a non-"0" character. – Cade Roux Mar 19 '09 at 14:09
  • True. It will return all the unmodified string of zeros in this case. If this is a problem, the return value of patindex will have to be tested against zero. – Ian Horwill Apr 20 '09 at 09:26
  • @Zapnologica: No. You'd have to put it in an "update TableName set ColumnName = ..." statement. – Ian Horwill Sep 19 '14 at 15:41
  • Sure, if you use Update Statements. – Srivastav Dec 22 '14 at 10:11
  • 3
    Before using this solution, please try to look into Arvo's answer [posted here](https://stackoverflow.com/questions/662383/better-techniques-for-trimming-leading-zeros-in-sql-server) – OscarSosa Jan 17 '19 at 14:31
  • Here's a better link to the answer mentioned by OscarSosa: https://stackoverflow.com/questions/662383/better-techniques-for-trimming-leading-zeros-in-sql-server#answer-662437 – derekbaker783 Apr 05 '22 at 15:25
32
select replace(ltrim(replace(ColumnName,'0',' ')),' ','0')
Ben
  • 51,770
  • 36
  • 127
  • 149
MTZ
  • 353
  • 3
  • 2
  • I received "Replace function requires 3 arguments." I believe it should read select replace(ltrim(replace(ColumnName,'0',' ')),' ','0') – brentlightsey Jan 10 '13 at 14:46
  • 6
    This will fail if the value has a space in it. Example: "0001 B" should become "1 B" but will become "10B" instead. – Omaer May 27 '14 at 17:41
  • 2
    Like @Omaer mentioned, this is not safe if there are some spaces in string. Improved solution - first replace spaces with char that is unlikely to get in input, and after 0-ltrim, restore back these chars to spaces after. In the end looks quite complex :( Example: select replace(replace(ltrim(replace(replace('000309933200,00 USD', ' ', '|'),'0',' ')),' ','0'), '|', ' ') --> 309933200,00 USD – Robert Lujo Jun 16 '16 at 12:23
9

You can use this:

SELECT REPLACE(LTRIM(REPLACE('000010A', '0', ' ')),' ', '0')
Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38
Stelian
  • 99
  • 1
  • 3
6

I had the same need and used this:

select 
    case 
        when left(column,1) = '0' 
        then right(column, (len(column)-1)) 
        else column 
      end
AHiggins
  • 7,029
  • 6
  • 36
  • 54
ekc
  • 61
  • 1
  • 1
5
select substring(substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 20), 
    patindex('%[^0]%',substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 
    20)), 20)

returns N0Z, that is, will get rid of leading zeroes and anything that comes before them.

Taryn
  • 242,637
  • 56
  • 362
  • 405
Nat
  • 51
  • 1
  • 1
3

If you want the query to return a 0 instead of a string of zeroes or any other value for that matter you can turn this into a case statement like this:

select CASE
      WHEN ColumnName = substring(ColumnName, patindex('%[^0]%',ColumnName), 10) 
       THEN '0'
      ELSE substring(ColumnName, patindex('%[^0]%',ColumnName), 10) 
      END
Ben
  • 51,770
  • 36
  • 127
  • 149
1

In case you want to remove the leading zeros from a string with a unknown size.

You may consider using the STUFF command.

Here is an example of how it would work.

SELECT ISNULL(STUFF(ColumnName
                   ,1
                   ,patindex('%[^0]%',ColumnName)-1
                   ,'')
             ,REPLACE(ColumnName,'0','')
             )

See in fiddler various scenarios it will cover

https://dbfiddle.uk/?rdbms=sqlserver_2012&fiddle=14c2dca84aa28f2a7a1fac59c9412d48

e-Fungus
  • 321
  • 3
  • 17
0

You can try this - it takes special care to only remove leading zeroes if needed:

DECLARE @LeadingZeros    VARCHAR(10) ='-000987000'

SET @LeadingZeros =
      CASE WHEN PATINDEX('%-0', @LeadingZeros) = 1   THEN 
           @LeadingZeros
      ELSE 
           CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) 
      END   

SELECT @LeadingZeros

Or you can simply call

CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) 
rsenna
  • 11,775
  • 1
  • 54
  • 60
0

Here is the SQL scalar value function that removes leading zeros from string:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vikas Patel
-- Create date: 01/31/2019
-- Description: Remove leading zeros from string
-- =============================================
CREATE FUNCTION dbo.funRemoveLeadingZeros 
(
    -- Add the parameters for the function here
    @Input varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result varchar(max)

    -- Add the T-SQL statements to compute the return value here
    SET @Result = @Input

    WHILE LEFT(@Result, 1) = '0'
    BEGIN
        SET @Result = SUBSTRING(@Result, 2, LEN(@Result) - 1)
    END

    -- Return the result of the function
    RETURN @Result

END
GO
Vikas
  • 24,082
  • 37
  • 117
  • 159
  • I'd try to avoid RBAR, personally: https://www.devonblog.com/continuous-delivery/unlock-true-potential-of-sql-server-by-avoiding-rbar-programming/ – derekbaker783 Apr 05 '22 at 15:21
-1

To remove the leading 0 from month following statement will definitely work.

SELECT replace(left(Convert(nvarchar,GETDATE(),101),2),'0','')+RIGHT(Convert(nvarchar,GETDATE(),101),8) 

Just Replace GETDATE() with the date field of your Table.

Kritner
  • 13,557
  • 10
  • 46
  • 72
Afzal
  • 9
-1

To remove leading 0, You can multiply number column with 1 Eg: Select (ColumnName * 1)

Krin
  • 11
  • 2
-3
select CASE
         WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0
           THEN ''
           ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)
       END
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • 1
    You should give explanation with your answers, not just a single code snippet. Also, please format code as code (there's a button along the top of the text-entry box). – Vivian Nov 29 '16 at 14:31
-3

you can try this SELECT REPLACE(columnname,'0','') FROM table

  • 4
    This will remove 0 irrespective of its position. Question is asking about only leading ones. – Sunil Jan 10 '18 at 02:03
-4

I borrowed from ideas above. This is neither fast nor elegant. but it is accurate.

CASE

WHEN left(column, 3) = '000' THEN right(column, (len(column)-3))

WHEN left(column, 2) = '00' THEN right(a.column, (len(column)-2))

WHEN left(column, 1) = '0' THEN right(a.column, (len(column)-1))

ELSE 

END

-5
select ltrim('000045', '0') from dual;

LTRIM
-----
45

This should do.

user3809240
  • 93
  • 1
  • 3
  • 18