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>
/// 是否匹配正则表达式
/// </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;
}

相关文章: