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

标签 c# sql-server sql-server-2008 sql-server-2005 sqlclr

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

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 ) );
    }
}

当执行 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 ) );
    }
}

最佳答案

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

System.Text.RegularExpressions.RegEx.IsMatch(字符串输入,字符串模式,RegexOptions 选项);

直接。

请注意, Debug模式下的工作方式与生产模式下的不同,SQL 会在需要时释放内存。

此外,尝试使用 RegexOptions.CompiledCultureInvariant

关于c# - 创建更快的正则表达式 clr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14413027/

相关文章:

sql - 智能感知接受快捷方式

sql - nvarchar 列大小对性能的影响

javascript - C# 与 Javascript 中的算术顺序

c# - VIsual Studio WinForm 连接到 SQL Server 数据库 : C# syntax to transfer the data

c# - Task.ContinueWith 在任务完成前触发

SQL Select WHERE Column NOT LIKE 跨多行

sql-server - 如何从两个不同表的两列中排序数据

sql-server - 重命名 SQL Server 架构名称

c# - selenium webdriver - 等待列表中最后一个类的 outerHTML 属性包含 "X"

c# - 检测持续时间值列表中的闪烁