I have a string of numbers that I need to trim a portion from using TSQL.
The string of numbers will always start with 101
then it will have a set of 0s
and a set of random numbers. Example:
1010000123456
I need to trim the 101 and the set of zeros. This is probably simple but I'm having all kinds of issues because I don't have a specific character to reference to using a CHARINDEX
and the possible combination of a 001
when the random numbers start that I need to keep is giving me issues using a PATINDEX
with a SUBSTRING
.
Best Answer
The
SUBSTRING(n, 3+PATINDEX('%[^0]%', SUBSTRING(n, 4, LEN(n))), LEN(n))
expression should work.SUBSTRING(n, 4, LEN(n))
PATINDEX()
with the'%[^0]%'
pattern to locate where the digits after the 0s start:PATINDEX('%[^0]%', SUBSTRING(n, 4, LEN(n)))
SUBSTRING()
and the previously found number (+3), to keep only the wanted digits (from the patindex number found up to the end.)Test at SQL-Fiddle