tags:

views:

38

answers:

1

Hi, I want to modify the following "extract numbers" function below to check if the first number in the output is "1", if so, delete the the "1" before displaying the output. THanks!

Ex.

Input: QW 1 RT 309
Output: 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
+2  A: 
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
Khorkrak
Thanks for your reply. when i try to execute your code i get the following error msg:'Msg 455, Level 16, State 2, Procedure ExtractNumbers, Line 13The last statement included within a function must be a return statement.'
gates
@gates - If you delete the last `else` that error should go away.
Martin Smith
ok I think I've fixed the bug - don't have or use SQL Server anymore so I can't test it to be certain but give it a whirl.
Khorkrak