Suppose you have a string that starts and ends in non-digits and has a series of digits in the middle e.g ‘A$B1234C*DE&’. The SQL below extracts the digits ‘1234’.
DECLARE @TestString VARCHAR(30) = 'A$B1234C*DE&'; -- non-digits & digits & non-digits SELECT @TestString AS 'Original_string' , PATINDEX('%[0-9]%',@TestString) AS 'Index_first_digit' , LEN(@TestString) - PATINDEX('%[0-9]%',REVERSE(@TestString)) + 1 AS 'Index_last_digit' , LEN(@TestString) - PATINDEX('%[0-9]%',@TestString) - PATINDEX('%[0-9]%',REVERSE(@TestString)) + 2 AS 'Number_of_digits' , SUBSTRING(@TestString , PATINDEX('%[0-9]%',@TestString) , LEN(@TestString) - PATINDEX('%[0-9]%',@TestString) - PATINDEX('%[0-9]%',REVERSE(@TestString)) + 2) AS 'Digits_only'
Output:
Original_string | Index_first_digit | Index_last_digit | Number_of_digits | Digits_only |
A$B1234C*DE& | 4 | 7 | 4 | 1234 |