Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL如何获取结束编号_Sql_Sql Server_String - Fatal编程技术网

SQL如何获取结束编号

SQL如何获取结束编号,sql,sql-server,string,Sql,Sql Server,String,我使用follow函数从字符串中获取数字 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

我使用follow函数从字符串中获取数字

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
在大多数情况下,它的使用起到了帮助作用

但不是全部

字符串如下所示:

string-goes-here-123450
string-2-goes-here-1233
在第一种情况下,输出是正确的,即123450,但在第二种情况下,输出是21233


我的问题是,我如何才能得到结尾数字的最后一位,它从“-”中分离出来。

试试这个。。。首先查找最后出现的
-
,然后取字符串的结尾

SET @pos = LEN(@string) - CHARINDEX('-',REVERSE(@string))

select  substr(@string, @pos+1, @len(@str))
编辑:可能是
@pos-1
。。。我在这台计算机上没有sql server,因此无法进行测试,mysql的函数差异很大,我不确定是否正确翻译了它。请尝试一下,让我知道

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
产生:-

input                    output
string-goes-here-123450  123450
string-2-goes-here-1233  1233

为什么21233不正确?因为结束号是我需要的产品id?这是mysql还是sql server?