• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

mysql 搞代码 4年前 (2022-01-09) 13次浏览 已收录 0个评论

有想过在T-Sql使用正则表达式吗?是的,完全可以的,我们可以用SQL SERVER CLR sql function来实现这一功能。

首先,我们在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

本文来源gaodai.ma#com搞#代!码网_

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感兴趣:


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:T-SQL中使用正则表达式函数

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址