A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
I added a couple of additional test cases.
Declare @Sample Table(MyData varchar(30));
Insert @Sample(MyData) Values
('123abc'), ---> 123
('123.98abc'), --> 123.98
('123 xy28'), --> 123
('123_xy_98'), -->123
('123_98_ab_00'), -->123
('A_123_123'), --> 123
('A-123-123'), --> 123
('A%xy125_123'), --> 125
('257'), -- 257
('257ABC'), -- 257
('abcdef') -- <empty string>;
;
;With cteFirstLoc As
(Select MyData, PatIndex('%[0-9.]%', MyData) As StartPos, Len(MyData) As DataLen
From @Sample),
cteLastLoc As
(Select MyData, StartPos, DataLen, PatIndex('%[^0-9^.]%', SubString(MyData, StartPos, DataLen)) As EndPos
From cteFirstLoc)
Select MyData, StartPos, EndPos,
Case When StartPos = 0 Then ''
When EndPos = 0 Then SubString(MyData, StartPos, DataLen)
Else SubString(MyData, StartPos, EndPos - 1)
End As Result
From cteLastLoc;
Tom