Removing leading zeroes from a field in a SQL stat

2019-01-02 17:45发布

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.

13条回答
刘海飞了
2楼-- · 2019-01-02 18:20
select CASE
         WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0
           THEN ''
           ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)
       END
查看更多
余生无你
3楼-- · 2019-01-02 18:23
select replace(ltrim(replace(ColumnName,'0',' ')),' ','0')
查看更多
浪荡孟婆
4楼-- · 2019-01-02 18:24
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.

查看更多
步步皆殇っ
5楼-- · 2019-01-02 18:25

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

查看更多
裙下三千臣
6楼-- · 2019-01-02 18:27

I had the same need and used this:

select 
    case 
        when left(column,1) = '0' 
        then right(column, (len(column)-1)) 
        else column 
      end
查看更多
旧时光的记忆
7楼-- · 2019-01-02 18:28

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)) 
查看更多
登录 后发表回答