SQL Server 2005支持用CLR語言(C# .NET、VB.NET)編寫過程、觸發(fā)器和函數(shù),因此使得正則匹配,數(shù)據(jù)提取能夠在SQL中靈活運用,大大提高了SQL處理字符串,文本等內(nèi)容的靈活性及高效性。
操作步驟:
1.新建一個SQL Server項目(輸入用戶名,密碼,選擇DB),新建好后,可以在屬性中更改的
2.新建一個類“RegexMatch.cs”,選擇用戶定義的函數(shù)
可以看到,該類為一個部分類:public partial class UserDefinedFunctions
現(xiàn)在可以在該類中寫方法了,注意方法的屬性為:[Microsoft.SqlServer.Server.SqlFunction]
現(xiàn)在類中增加以下兩個方法:

/// 是否匹配正則表達式
/// </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.下一步就是部署的問題了,點擊項目右鍵--》部署即可
提示部署成功了,可以在數(shù)據(jù)庫的標量值函數(shù)中多了這兩個方法了。
使用方法和正常的SQL函數(shù)一樣:
select dbo.RegexMatch('/Book/103.aspx','/book/("d+).aspx','true')
消息 6263,級別 16,狀態(tài) 1,第 1 行
禁止在 .NET Framework 中執(zhí)行用戶代碼。啟用 "clr enabled" 配置選項。
——出現(xiàn)此錯誤,配置下:
exec sp_configure 'clr enabled',1;
reconfigure with override;
是否匹配:
select dbo.RegexMatch('/Book/103.aspx','/book/("d+).aspx','true')
返回1,表示匹配成功
select dbo.RegexMatch('/Book/103.aspx','/book/("d+).aspx','false')
表示0,匹配失敗(不忽略大小寫)。
數(shù)據(jù)提取:
select dbo.GetRegexMatchGroups('/Book/103.aspx','/book/("d+).aspx',1,50)
注意:SQL中使用CLR時,盡量使用try catch…以免出現(xiàn)異常
作者:MaoBisheng
出處:http://maobisheng.cnblogs.com/
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權(quán)利。