Here is the technique for trimming leading zeros in SQL:
SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col))
This will find the first non-zero character in ‘str_col, Adding '.’ ` will ensure that it always finds a position, even if the string contains all zeros.
The whole code extracts the part of the string starting from the non-zero character till the end.
This technique will remove zeros from numeric strings and make the result even cleaner and more readable
Example:
USE tempdb
GO
-- Create sample table
CREATE TABLE Table1 (Col1 VARCHAR(100))
INSERT INTO Table1 (Col1)
SELECT '0001'
UNION ALL
SELECT '000100'
UNION ALL
SELECT '100100'
UNION ALL
SELECT '000 0001'
UNION ALL
SELECT '00.001'
UNION ALL
SELECT '01.001'
UNION ALL
SELECT '0000'
GO
SELECT
CASE PATINDEX('%[^0 ]%', Col1 + ' ')
WHEN 0 THEN ''
ELSE SUBSTRING(Col1, PATINDEX('%[^0 ]%', Col1 + ' '), LEN(Col1))
END
FROM Table1