SQLServer中使⽤正则表达式
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函数⼀样:
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;
是否匹配:
dbo.RegexMatch('/Book/103.aspx','/book/(\d+).aspx',1)
返回1,表⽰匹配成功
dbo.RegexMatch('/Book/103.aspx','/book/(\d+).aspx',0)
正则表达式任意内容
表⽰0,匹配失败(不忽略⼤⼩写)。
数据提取:
dbo.GetRegexMatchGroups('/Book/103.aspx','/book/(\d+).aspx',1,50)
返回103,⾮常⽅便的提取。
注意:SQL中使⽤CLR时,尽量使⽤try catch…以免出现异常。