簡體   English   中英

使用正則表達式匹配SQL查詢

[英]Match SQL queries using Regular Expressions

我想匹配可能具有不同參數的相同類型的SQL查詢。 例如

SELECT Name 
FROM Production.Product 
WHERE Name = 'Bearing Ball' and ProductNumber = 'BA-8327'

SELECT Name 
FROM Production.Product 
WHERE Name = 'Cycle' and ProductNumber = 'CY-1234'

是具有不同參數的相同類型的查詢。 在第一個示例中,基本上任何東西都可以代替“軸承滾珠”和“ BA-8327”。 參數可以是字符串,數字或帶空格或不帶空格的日期。 我嘗試了以下表達式:

var result = new Regex("SELECT Name FROM Production.Product WHERE Name = '*' and ProductNumber = '*'").IsMatch(query)

它沒有按預期工作。 請給我一個解決方案。

*不是通配符。 我將其替換為('([^']|'')*'|\\d+) ,該字符串與單引號字符串匹配,該字符串包含0或0次以上的字符,而不包含'或連續'' (轉義的單引號)以外'字符。 或者,它匹配一個或多個連續數字。

以前有一篇帖子(已被刪除)提到轉義. 通配符。 這是一個很好的建議,我也更新了我的答案以反映這一點。

var result = new Regex(@"SELECT Name FROM Production\.Product WHERE Name = ('([^']|'')*'|\d+) and ProductNumber = ('([^']|'')*'|\d+)").IsMatch(query);

這是一個在正則表達式解析后將所有重要數據轉換為動態實體的系統。 這樣,您可以確定操作是否相同。 否則,您可以查看模式並向其中添加內容以正確讀取數據,例如使用\\x27([^\\x27]+)\\x27來匹配'Bearing Ball' ,這可以滿足您的模式需求。


string pattern = @"
^                     # Start of the line
select\s              # Anything not in brackets do not capture.
(?<What>[^\s]+)       # Capture a name most likely
\sfrom\s
(?<Table>[^\s]+)      # Capture Table name
\swhere\s
\1                    # Name(?) the what, must be used again
\s*=\s*
\x27                  # \x27 is a single quote '
(?<Name>[^\x27]+)     # Read up to the next quote for the what.
\x27
\s+and\s+ProductNumber\s*=\s*
\x27
(?<ProdNumber>[^\x27]+)  # Read up to the next quote for the product number.
";

string data = @"
SELECT Name FROM Production.Product WHERE Name = 'Bearing Ball' and ProductNumber = 'BA-8327'
SELECT Name FROM Production.Product WHERE Name = 'Cycle' and ProductNumber = 'CY-1234'
";

// IgnorePatternWhitespace lets us space out and comment the pattern code only. Does not affect regex processing.
Regex.Matches(data, pattern, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline)
     .OfType<Match>()
     .Select(mat => new
     {
        Table = mat.Groups["Table"].Value,
        What = mat.Groups["What"].Value,
        Name  = mat.Groups["Name"].Value,
        ProductNumber = mat.Groups["ProdNumber"].Value
     });

2個動態實體的結果

在此處輸入圖片說明

看看Arvind Shyamsundar在MSDN上發布的博客,它確實可以滿足您的需求,並且可以適應更多需求。 它使用ScriptDom類,Microsoft自己的T-SQL解析器和生成器代碼,這似乎比嘗試自己解析諸如T-SQL之類的復雜語言要好得多。 使用transactsql scriptdom類標准化T-SQL文本

請注意,一組名為ScriptDom的類位於2個不同的命名空間中。 SQL Server 2012附帶的SQL Server附帶一個您應該使用的名稱,其名稱空間為Microsoft.SqlServer.TransactSql.ScriptDom。 名稱空間為Microsoft.Data.Schema.ScriptDom的是一個較舊的,效力較低的版本,該版本以前隨Visual Studio一起提供。 您不應再在任何新項目中使用后者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM