创建更快的正则表达式clr函数

ca9*_*3d9 6 c# sql-server sql-server-2005 sqlclr sql-server-2008

我正在尝试在链接http://msdn.microsoft.com/en-us/magazine/cc163473.aspx中改进Clr功能.

public static partial class UserDefinedFunctions 
{
    public static readonly RegexOptions Options =
        RegexOptions.IgnorePatternWhitespace |
        RegexOptions.Singleline;

    [SqlFunction]
    public static SqlBoolean RegexMatch(
        SqlChars input, SqlString pattern)
    {
        Regex regex = new Regex( pattern.Value, Options );
        return regex.IsMatch( new string( input.Value ) );
    }
}
Run Code Online (Sandbox Code Playgroud)

执行时select * from Table1 where dbo.RegexMatch(col1, 'pattern') = 1,Clr函数为表中的每一行创建一个新的Regex对象.

是否可以为每个Sql语句只创建一个Regex对象?对于每一行只需致电regex.Ismatch(...).以下代码是否有效?

public static partial class UserDefinedFunctions 
{
    public static readonly RegexOptions Options =
        RegexOptions.IgnorePatternWhitespace |
        RegexOptions.Singleline;

    static Regex regex = null;

    [SqlFunction]
    public static SqlBoolean RegexMatch(
        SqlChars input, SqlString pattern)
    {
        if (regex == null) 
            regex = new Regex( pattern.Value, Options );
        return regex.IsMatch( new string( input.Value ) );
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 2

您的静态正则表达式的基于 UDF 的实例可能甚至不会被重复使用,您最好调用静态版本

System.Text.RegularExpressions.RegEx.IsMatch(string input, string pattern, RegexOptions options);

直接地。

请注意,在调试模式下,事情的工作方式与生产环境中的工作方式不同,并且 SQL 将在需要时释放内存。

另外,尝试使用RegexOptions.CompiledCultureInvariant