How to remove leading and trailing characters when they are "0" in SQL Server
4 answers
This also works for leading and trailing zeros at the same time:
declare @s varchar(15) = '00abc00efg000'
select substring(@s,
patindex('%[^0]%', @s),
len(@s)-patindex('%[^0]%', reverse(@s))-patindex('%[^0]%', @s)+2);
Description: This is the substring from the first nonzero character to the first nonzero character in the inverted string.
+2
source to share
Say your data exists in a column Col1
then this expression should do this
select CASE
WHEN RIGHT(col1 , 1) = '0'
THEN SUBSTRING(col1,0,PATINDEX('%[A-Z1-9]%',REVERSE(col1)))
WHEN LEFT(col1 , 1) = '0'
THEN SUBSTRING(col1,PATINDEX('%[A-Z1-9]%',col1),LEN(col1))
ELSE
Col1
END AS 'ParsedCol1'
FROM Data
+2
source to share
This might work for SQL as it removes the leading and trailing "000" from your string.
SELECT TRIM(BOTH ‘000’ FROM
‘your_data_table_column’);
More details
http://www.w3resource.com/mysql/string-functions/mysql-trim-function.php
0
source to share