微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

T-SQL中使用正则表达式函数

首先,我们在VSTS中创建一Database Project,增一个class,实现下面的一个方法
<div class="codetitle"><a style="CURSOR: pointer" data="21465" class="copybut" id="copybut21465" onclick="doCopy('code21465')"> 代码如下:

<div class="codebody" id="code21465">
///
/// Regs the ex match.
///

/// <param name="inputValue">The input value.
/// <param name="regexPattern">The regex pattern.
/// Author: Petter Liu http://wintersun.cnblogs.com
/// 1 match,0 not match
[sqlFunction]
public static bool RegExMatch(string inputValue,string regexPattern)
{
// Any nulls - we can't match,return false
if (string.IsNullOrEmpty(inputValue) || string.IsNullOrEmpty(regexPattern))
return false; Regex r1 = new Regex(regexPattern.TrimEnd(null));
return r1.Match(inputValue.TrimEnd(null)).Success;
}

好了,Build后Deploy到你的Target database就OK了,VisualStudio自动注册这个程序集的。如果,你想手动注册程序集,可执行以下的T-sql:
<div class="codetitle"><a style="CURSOR: pointer" data="75789" class="copybut" id="copybut75789" onclick="doCopy('code75789')"> 代码如下:
<div class="codebody" id="code75789">
CREATE ASSEMBLY [RegExCLR] FROM 'RegExCLR.dll'; -- Add the REGEX function. We want a friendly name
-- RegExMatch rather than the full namespace name.
-- Note the way we have to specify the Assembly.Namespace.Class.Function
-- NOTE the RegExCLR.RegExCLR
-- (one is the assembly the other is the namespace)
CREATE FUNCTION RegExMatch ( @inputCalue NVARCHAR(4000),
@regexPattern NVARCHAR(4000) ) RETURNS BIT
AS EXTERNAL NAME RegExCLR.RegExCLR.ClrClass.RegExMatch;

OK,一切OK的后,我们来测试下: select COUNT(1) from Threads where dbo.RegExMatch(ThreadId,'^[{|(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[)|}]?$')=1
上面的T-sql是找出Threads表ThreadId是GUID的记录数。 等于1是匹配,^[{|(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[)|}]?$ 匹配GUID的正则表达式。 完了,希望这篇POST对您有帮助。您可能对以下POST感兴趣: SQLSERVER2008中CTE的Split与CLR的性能比较 SQLSERVER使用CLR Stored Procedure导出数据到Excel

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐