加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 07:57:00 所属栏目:MsSql教程 来源:网络整理
导读:感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧! 首先,我们在VSTS中创建一Database Project,增一个class,实现下面的一个方法: 代码如下: /// summary /// Regs the ex match. /// /summary /// param name=inputValueThe input value

感兴趣的小伙伴,下面一起跟随编程之家 52php.cn的小编两巴掌来看看吧!

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

代码如下:

 
/// <summary> 
/// Regs the ex match. 
/// </summary> 
/// <param name="inputValue">The input value.</param> 
/// <param name="regexPattern">The regex pattern.</param> 
/// <remarks>Author: Petter Liu http://wintersun.cnblogs.com </remarks> 
/// <returns>1 match,0 not match</returns> 
[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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读