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

首先,我们在VSTS中创建一Database Project,增一个class, 实现下面的一个方法:

///

/// Regs the ex match.

///

/// The input value.

/// 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:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值