【发布时间】:2013-01-02 23:54:06
【问题描述】:
我正在尝试改进链接 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 ) );
}
}
执行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 ) );
}
}
【问题讨论】:
-
文章建议如果你使用
RegexOptions.Compiled,那么它可能会被缓存——但我看不到任何其他证据...... -
有趣。 Regex 的构造函数将重用 Regex 实例,如果它具有已编译的选项和相同的模式?我在想一些单例模式,但不确定单例的寿命。
-
它不会重用相同的实际实例,但它可以重用所有已完成的工作来创建前一个实例。
-
您只是将竞争条件放入 SQL Server 并破坏了它的可靠性。并发查询将在彼此的正则表达式上乱写。这就是它被禁止的原因。 (有解决方法。)
-
msdn 链接已失效。
标签: c# sql-server sql-server-2008 sql-server-2005 sqlclr