I'm working on a project to parse through numerous varchar max fields for multiple occurrences of specific patterns. For example, a cemetery plot was originally sold on 2/14/1928, then deeded on 7/4/1975 and deeded again on 12/31/2010. PATINDEX works great for finding the first instance of a pattern but obviously doesn't work for finding multiple occurrences. To get around this, I wrote the stored procedure below and it works well for identifying multiple instances of a pattern. I was hoping to create it as a function but I discovered that executing SQL statements in a function is a no go. I'm having a difficult time thinking of different ways I could rewrite this so it would work as a function and I'm hoping some of you T-SQL rockstars may be able to offer some suggestions. Thank you in advance for any help you can offer!
Executing the following statement identifies the third occurrence of a lowercase letter next to a number and correctly returns 10 as the starting position of the occurrence.
EXEC dbo.PATINDEX2 @TargetStr = '%[a-z][0-9]%', @SearchedStr = 'abc1acc2ba6d', @Occurrence = 3
This is the stored procedure:
CREATE PROCEDURE [dbo].[PATINDEX2] (@TargetStr VARCHAR(MAX),@SearchedStr VARCHAR(MAX),@Occurrence INT) AS
BEGIN
DECLARE @TSQL VARCHAR(MAX),
@TempSearchStr VARCHAR(MAX),
@Position INT,
@Counter INT,
@ReturnValue INT,
@PositionSum INT = 0
DECLARE @TempCharPos TABLE
(
[ID] INT IDENTITY(1, 1),
CharPos INT
)
SET @TSQL = 'SELECT PATINDEX(''' + @TargetStr + ''', ''' + @SearchedStr + ''')'
INSERT INTO @TempCharPos
EXEC(@TSQL)
SET @Position = (SELECT CharPos
FROM @TempCharPos
WHERE [ID] IN (SELECT MAX([ID])
FROM @TempCharPos))
SET @Counter = 1
SET @PositionSum = @PositionSum + @Position
IF @Occurrence = 1
SET @ReturnValue = @Position
ELSE
BEGIN
WHILE ( @Counter < @Occurrence )
BEGIN
SET @TempSearchStr = SUBSTRING(@SearchedStr, @PositionSum + 1, LEN(@SearchedStr) + 1)
SET @TSQL = 'SELECT PATINDEX(''' + @TargetStr + ''', ''' + @TempSearchStr + ''')'
INSERT INTO @TempCharPos
EXEC(@TSQL)
SET @Position = (SELECT CharPos
FROM @TempCharPos
WHERE [ID] IN (SELECT MAX([ID])
FROM @TempCharPos))
SET @PositionSum = @PositionSum + @Position
SET @ReturnValue = @PositionSum
SET @Counter = @Counter + 1
END
END
SELECT ( @ReturnValue )
END
GO
REGEXP_INSTR
is available7/4/1975
or12/31/2010
how would you usePATINDEX
anyway? It has no syntax to say "match 1 or 2 digits"