Find the First Occurrence of a Pattern Using Regular Expression in T-SQL
February 25th, 2009 by Andrew Chen
I was looking for a way to find the first occurrence of 4 digit
select dbo.fn_regex (’[1-2][0,9][0-9][0-9]’, ‘free form text’),
to return the first matching substring. This function can be use on SQL 2000 and SQL 2005. However in SQL 2005 it is better to use CLR function. You can refer to the following link for further detail.
T-SQL regular expression in SQL 2000
T-SQL regular expression in SQL 2005
create FUNCTION
dbo.fn_regex(@pattern varchar(255), @matchstring varchar(8000))
RETURNS varchar(100)
AS
BEGIN
declare @obj int
declare @res int
declare @match bit
declare @objMatch int
declare @matchpart varchar(100)
set @match=0
exec @res=sp_OACreate ‘VBScript.RegExp’,@obj OUT
IF (@res <> 0) BEGIN
RETURN NULL
END
exec @res=sp_OASetProperty @obj, ‘Pattern’, @pattern
IF (@res <> 0) BEGIN
RETURN NULL
END
exec @res=sp_OASetProperty @obj, ‘IgnoreCase’, 1
IF (@res <> 0) BEGIN
RETURN NULL
END
–exec @res=sp_OAMethod @obj, ‘Test’,@match OUT, @matchstring
–IF (@res <> 0) BEGIN
— RETURN NULL
–END
exec @res= sp_OAMethod @obj, ‘execute’, @objMatch OUT, @matchstring
IF (@res <> 0)
RETURN NULL
ELSE
EXEC @res= sp_OAGetProperty @objmatch, ‘item(0).value’, @matchpart OUT
exec @res=sp_OADestroy @obj
–return @match
return @matchpart
END


No comments yet.