i want to find first integer value from varchar column

Viewed 161

i have below data in table.

ID
test_SQL_01
test_SQL_02_PQR_01
test_SQL_03_055
test_SQL_04_ABC_99

i want Output like below.

ID
01
02
03
04
2 Answers

If the INTERGER value has always 2 digits then yo can do :

select substring(ID, patindex('%[0-9]%', ID), 2) as ID
from table t;

This method can handle embedded numbers of different length

Testdata:

DECLARE @t table(ID varchar(50))
INSERT @t values
('1'),
('2abc'),
('a3'),
('test_SQL_01'),
('test_SQL_02_PQR_01'),
('test_SQL_03_055'),
('test_SQL_04_ABC_99')

Query:

SELECT 
  STUFF(LEFT(ID, patindex('%[0-9][^0-9]%', ID + 'x')), 1, 
    patindex('%[^0-9][0-9]%', ID), '')
FROM @t

Result:

1
2
3
01
02
03
04
Related