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条回答
伤终究还是伤i
2楼-- · 2019-01-02 18:29

You can use this:

SELECT REPLACE(LTRIM(REPLACE('000010A', '0', ' ')),' ', '0')
查看更多
萌妹纸的霸气范
3楼-- · 2019-01-02 18:34

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

查看更多
千与千寻千般痛.
4楼-- · 2019-01-02 18:35
select ltrim('000045', '0') from dual;

LTRIM
-----
45

This should do.

查看更多
只若初见
5楼-- · 2019-01-02 18:36

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
查看更多
流年柔荑漫光年
6楼-- · 2019-01-02 18:36

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

查看更多
呛了眼睛熬了心
7楼-- · 2019-01-02 18:39
select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
查看更多
登录 后发表回答