SQL Server 2005及以上版本支持用CLR語言(C# .NET、VB.NET)編寫過程、觸發器和函數,因此使得正則匹配,數據提取能夠在SQL中靈活運用,大大提高了SQL處理字符串,文本等內容的靈活性及高效性。
操作步驟:
1.新建一個SQL Server項目(輸入用戶名,密碼,選擇DB),新建好后,可以在屬性中更改的
2.新建一個類“RegexMatch.cs”,選擇用戶定義的函數
可以看到,該類為一個部分類:public partial class UserDefinedFunctions
現在可以在該類中寫方法了,注意方法的屬性為:[Microsoft.SqlServer.Server.SqlFunction]
現在類中增加以下兩個方法:
/// 是否匹配正則表達式 /// </summary> /// <param name="input">輸入的字符串</param> /// <param name="pattern">正則表達式</param> /// <param name="ignoreCase">是否忽略大小寫</param> /// <returns></returns> [Microsoft.SqlServer.Server.SqlFunction] public static bool RegexMatch(string input, string pattern, bool ignoreCase) { bool isMatch = false; if (!string.IsNullOrEmpty(input) && !string.IsNullOrEmpty(pattern)) { try { Match match = null; if (ignoreCase) match = Regex.Match(input, pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled); else match = Regex.Match(input, pattern, RegexOptions.Multiline | RegexOptions.Compiled); if (match.Success) isMatch = true; } catch { } } return isMatch; } /// 獲取正則表達式分組中的字符 /// </summary> /// <param name="input">輸入的字符串</param> /// <param name="pattern">正則表達式</param> /// <param name="groupId">分組的位置</param> /// <param name="maxReturnLength">返回字符的最大長度</param> /// <returns></returns> [Microsoft.SqlServer.Server.SqlFunction] public static string GetRegexMatchGroups(string input, string pattern, int groupId, int maxReturnLength) { string strReturn = string.Empty; if (!string.IsNullOrEmpty(input) && !string.IsNullOrEmpty(pattern)) { try { Match match = Regex.Match(input, pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled); if (match.Success && (groupId < match.Groups.Count)) { strReturn = match.Groups[groupId].Value; strReturn = (strReturn.Length <= maxReturnLength) ? strReturn : strReturn.Substring(0, maxReturnLength); } } catch { return string.Empty; } } return strReturn; }
3.下一步就是部署的問題了,點擊項目右鍵--》部署即可
提示部署成功了,可以在數據庫的標量值函數中多了這兩個方法了。
使用方法和正常的SQL函數一樣:
select dbo.RegexMatch('/Book/103.aspx','/book/(\d+).aspx','true')
消息 6263,級別 16,狀態 1,第 1 行
禁止在 .NET Framework 中執行用戶代碼。啟用 "clr enabled" 配置選項。
——出現此錯誤,配置下:
exec sp_configure 'clr enabled',1;
reconfigure with override;
是否匹配:
select dbo.RegexMatch('/Book/103.aspx','/book/(\d+).aspx',1)
返回1,表示匹配成功
select dbo.RegexMatch('/Book/103.aspx','/book/(\d+).aspx',0)
表示0,匹配失敗(不忽略大小寫)。
數據提取:
select dbo.GetRegexMatchGroups('/Book/103.aspx','/book/(\d+).aspx',1,50)
返回103,非常方便的提取。
注意:SQL中使用CLR時,盡量使用try catch…以免出現異常。