简体   繁体   中英

SQL How to get the ending number

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 "-"

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM