修改sql函数,删除string中的第一个字符

时间:2010-07-16 21:06:40

标签: sql function

我想修改下面的“提取数字”功能,检查输出中的第一个数字是否为“1”,若是,则在显示输出前删除“1”。谢谢!

实施例。

输入:QW 1 RT 309
输出:309

create

function [dbo].[ExtractNumbers](@Numbers nvarchar(2000)) 
returns

nvarchar(2000) 
as

BEGIN

declare

@NonNumericIndex int 
set

@NonNumericIndex = PATINDEX('%[^0-9]%',@Numbers) 
WHILE

@NonNumericIndex > 0 
begin



SET

@Numbers = REPLACE(@Numbers,SUBSTRING(@Numbers,@NonNumericIndex,1),'') 
SET

@NonNumericIndex = PATINDEX('%[^0-9]%',@Numbers) 

SET

end



return

@Numbers 
END

1 个答案:

答案 0 :(得分:2)

create function [dbo].[ExtractNumbers](@Numbers varchar(2000)) returns nvarchar(2000) as  
begin
   declare @NonNumericIndex int 
   set @NonNumericIndex = patindex('%[^0-9]%',@Numbers) 
   while @NonNumericIndex > 0 
   begin
      set @Numbers = replace(@Numbers,SUBSTRING(@Numbers,@NonNumericIndex,1),'') 
      set @NonNumericIndex = PATINDEX('%[^0-9]%',@Numbers) 
   end
   if left(@Numbers, 1) <> '1'
      set @Numbers = right(@Numbers, len(@Numbers) - 1)
   return @Numbers
end