Tuesday 23 March 2010

Extract Numbers / Text from String

Create Function Extract(@NumStr Varchar(1000), @option int = 0)
returns Varchar(1000)
as
Begin
Declare @tmpStr Varchar(1000), @c int, @n int
Declare @Result Varchar(1000)
select @Result = '', @n = 1
While @NumStr != ''
Begin
select @c = CHARINDEX(' ', @NumStr, @n)
if (@c = 0) Break;
select @tmpStr = SUBSTRING(@NumStr, @n, @c)

if (@option = 0)
Begin
if (@tmpStr like '%[0-9]%')
set @Result = @Result + @tmpStr
End
else
Begin
if (@tmpStr Not like '%[0-9]%')
set @Result = @Result + @tmpStr
End
select @NumStr = SUBSTRING(@NumStr, @c + 1, 1000)
End
if (@option = 0)
Begin
if (@numStr like '%[0-9]%')
set @Result = @Result + @numStr
End
else
Begin
if (@numStr Not like '%[0-9]%')
set @Result = @Result + @numStr
End
Return (@Result);
End


go

-- Test
select dbo.Extract('This string contains 5 words and3 now 9 words. And also 9ahs asd', 1)

No comments:

Post a Comment