The duplicate flag raised in the comments will point you to a working answer, but you need to expand the length of SUBSTRING()
to handle your data type.
For example, if you tried to copy the code exactly and run:
DECLARE @x VARCHAR(100)
SET @x = '0000HUJ8 9IU877 8UJH'
SELECT SUBSTRING(@x, PATINDEX('%[^0]%', @x), 10) -- note this uses '10'
You'll get the wrong result, HUJ8 9IU87
. This has nothing to do with the extra space: you simply are telling SUBSTRING()
that you want ten characters, and it's giving you ten characters (which coincidentally goes up to the space).
If you expand the SUBSTRING()
to a longer value, as in the following code, it will work as expected:
DECLARE @x VARCHAR(100)
SET @x = '0000HUJ8 9IU877 8UJH'
SELECT SUBSTRING(@x, PATINDEX('%[^0]%', @x), 100) -- note this now uses '100'
Set the length argument for SUBSTRING()
to be whatever you need from your data type, and it will work correctly: it returns HUJ8 9IU877 8UJH
.
EDIT:
if you want to remove leading spaces, in addition to leading zeroes, you'll need to change the formula to LTRIM(SUBSTRING(LTRIM(@x), PATINDEX('%[^0]%', @x), 100))
: I put LTRIM()
in there twice to handle leading spaces before removing zeroes, and after removing zeroes.