我正在尝试改进链接中的 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.Compiled
和 CultureInvariant
。
关于c# - 创建更快的正则表达式 clr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14413027/