Reputation: 133
I was using follow function to get numbers from a string.
CREATE FUNCTION dbo.udf_GetNumeric
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END
GO
And the usage of it helped in most cases.
But not in all.
Strings looks like this:
string-goes-here-123450
string-2-goes-here-1233
In the first case, output was correct which is 123450, but in second, the output was 21233.
My question is how can i just get the last bit of ending number which separates from "-"
Upvotes: 1
Views: 664
Reputation: 1715
create table #test(
input varchar(50)
)
go
insert into #test values
('string-goes-here-123450'),
('string-2-goes-here-1233')
go
select t.input, right(t.input,charindex('-',reverse(t.input))-1) as output
from #test t
produces:-
input output
string-goes-here-123450 123450
string-2-goes-here-1233 1233
Upvotes: 1
Reputation: 5911
try this... first find the last occurance of -
and then take the end of the string
SET @pos = LEN(@string) - CHARINDEX('-',REVERSE(@string))
select substr(@string, @pos+1, @len(@str))
EDIT: it might be @pos-1
... I don't have sql server on this computer so I can't test and the functions for mysql are different enough that I'm not sure I translated it correctly. Please try this out and let me know.
Upvotes: 1