Regular expression to match T-SQL variable declarations
Is is possible, using a regular expression, to match all T-SQL variable names following a declare
statement?
In the following, I'd like to match Var1
, Var2
, and Var3
. I do not want to match later references to these variables.
declare
@Var1 datetime,
@Var2 int,
@Var3 varchar(max)
I've been working on it for some time using RegexBuddy and can't seem to get it right. I'm starting to wonder if it's po开发者_如何学编程ssible.
EDIT:
Here's what I've got so far. It only matches the first variable. I can't figure out how to match subsequent ones.
(?i:declare)\s+
(?:@([\w@$#]+)\s+(?:bigint|int|smallint|tinyint
|(?:(?:decimal|numeric)(?:\s*\(\s*\d+(?:\s*,\s*\d+)\s*\))?)
|money|smallmoney
|(?:(?:float|datetime2|datetimeoffset|time|char|varchar|nchar
|nvarchar|binary|varbinary)(?:\s*\(\s*\d+\s*\))?)
|real|date|smalldatetime|datetime|text|ntext|image
|uniqueidentifier|xml))
Here's what I came up with, I simplified it a little (got rid of all the specific data types) but you can fix it up how you like:
(?i:declare|,)\s+?(?:(?<var>@[\w@$#]+)\s+(?<type>[\w()]+))+
The key is the very first part, you want to look for the keyword "declare" or a "," these are going to be your separators. Now techinically this means it would also match on something like this:
@var1 int,
@var2 int,
@var3 int
But since this would be invalid T-SQL anyways, I'm letting that go.
精彩评论