Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first leading 0 from varchar with MSSQL

How I can remove only the first 0 character from a varchar?

For example '000303' ==> '00303'

I tried this without success, all the 0 characters are removed:

SELECT SUBSTRING('000303', PATINDEX('%[^0]%', '000303'),LEN('000303'));

Thanks

like image 864
Maxime Avatar asked May 27 '15 17:05

Maxime


People also ask

How do I remove the first character from a varchar in SQL?

To delete the first characters from the field we will use the following query: Syntax: SELECT SUBSTRING(string, 2, length(string));

How do I remove zeros from a number in SQL Server?

Save this answer. Show activity on this post. SELECT CEIL((AVG(salary)) - (AVG(REPLACE(salary, '0', '')))) AS avg_salary FROM employees; REPLACE() : used to remove 0 from salary.

How do I remove the beginning of a string in SQL?

SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.


2 Answers

Try using STUFF Function

SELECT CASE WHEN LEFT('000303',1) = '0' THEN STUFF('000303',1,1,'') ELSE '000303' END

or Use RIGHT Function

SELECT CASE WHEN LEFT('000303',1) = '0' THEN RIGHT('000303', LEN('000303')-1) ELSE '000303' END

Instead of LEFT('000303',1) = '0' check you can also use

charindex('0','000303') = 1 or

'000303' LIKE '0%' (ughai suggestion)

like image 92
Pரதீப் Avatar answered Dec 02 '22 22:12

Pரதீப்


Try this:

SELECT RIGHT(MyColumn, LEN(MyColumn) - 1) 

This will remove the first character from the varchar column.

If it is specific to 0 then try this:

SELECT CASE WHEN LEFT(MyColumn,1) = '0' 
     THEN RIGHT(MyColumn, LEN(MyColumn) - 1)  
     ELSE
     MyColumn END
like image 41
Rahul Tripathi Avatar answered Dec 02 '22 20:12

Rahul Tripathi