I have been working on some legacy code in our application that detects certain keywords in the text of an SQL stored procedure by using Regex and I have found a bug that I can’t quite correct due to my limited knowledge of Regex.
Basically the regex that I currently have works in all but one case:
(?<=\n\s*)(?<!with.*[\s\S]*)as
It should return a match on this version of a stored procedure:
ALTER PROCEDURE [dbo].[p_obj_name_with_something]
@username [nvarchar](100) = null,
@id [int] = null,
@mode [int] = 0
AS
/*-------------------------------------------------------------------------
However it shouldn’t for this version, but it currently does return a match:
ALTER PROCEDURE [dbo].[p_obj_name_with_something]
@username [nvarchar](100) = null,
@id [int] = null,
@mode [int] = 0
WITH EXECUTE AS CALLER
AS
/*-------------------------------------------------------------------------
I want a match when the keyword WITH isn’t found before the AS keyword, but it will allow the word within the name or parameters of the stored procedure.
The way I think the detection would work is if the keyword WITH has whitespace (or a newline) either side of it, but I can’t quite figure out the regex syntax.
Any suggestions?
Even though it isn’t a real answer, I found the easier way to do this was to enforce some naming convention rules in our stored procedures and modify the 20 or so that violated the rules.
Indeed, this is a case when Regex is not the solution!