从字符串中获取数字部分

时间:2014-08-30 10:53:44

标签: sql sql-server sql-server-2008 tsql sql-server-2012

我有一个关于从第一次出现的任何字符串中获取数字的查询。例如

"10 Main Street"        would return 10
"34 10 Main Street"     would return 3410
"  34 10 Main Street"   would return 3410
"  34 - 10 Main Street" would return 34

功能

ALTER FUNCTION [dbo].[GetNumeric]
(@strAlphaNumeric nVARCHAR(Max))
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

但这并不能提供准确的答案,

select dbo.[GetNumeric]('  34 - 10 Main Street' )

结果是 - 3410 //这是错误的

1 个答案:

答案 0 :(得分:1)

这是逻辑,似乎做你想要的:

declare @pattern varchar(8000) = 'asd   34-2 xx - 35 abc'
declare @firstnum int;

select @pattern = replace(@pattern, ' ', '');
select @firstnum = patindex('%[0-9]%', @pattern);

select substring(@pattern, @firstnum,
                 patindex('%[^0-9]%', substring(@pattern, @firstnum, len(@pattern))) - 1
                );

编辑:

要修复字符串末尾的数字问题:

选择@pattern = replace(@pattern,'',''); 选择@firstnum = patindex('%[0-9]%',@ pattern); 选择@firstafternum = patindex('%[^ 0-9]%',substring(@pattern,@ firstnum,len(@pattern))) - 1;

select substring(@pattern, @firstnum,
                 (case when @firstafternum > 0 then @firstafternum
                       else len(@pattern)
                  end) 
                );