时间:2021-07-01 10:21:17 帮助过:37人阅读
有想过在T-Sql使用正则表达式吗?是的,完全可以的,我们可以用SQL SERVER CLR sql function来实现这一功能。
首先,我们在VSTS中创建一Database Project,增一个class, 实现下面的一个方法:
- <br>/// <summary> <br>/// Regs the ex match. <br>/// </summary> <br>/// <param name="inputValue">The input value. <br>/// <param name="regexPattern">The regex pattern. <br>/// <remarks>Author: Petter Liu http://wintersun.cnblogs.com </remarks> <br>/// <returns>1 match,0 not match</returns> <br>[SqlFunction] <br>public static bool RegExMatch(string inputValue, string regexPattern) <br>{ <br>// Any nulls - we can't match, return false <br>if (string.IsNullOrEmpty(inputValue) || string.IsNullOrEmpty(regexPattern)) <br>return false; <br><br>Regex r1 = new Regex(regexPattern.TrimEnd(null)); <br>return r1.Match(inputValue.TrimEnd(null)).Success; <br>} <br> <br>好了,Build后Deploy到你的Target database就OK了,VisualStudio会自动注册这个程序集的。如果,你想手动注册程序集,可执行以下的T-SQL: <br> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>CREATE ASSEMBLY [RegExCLR] FROM 'RegExCLR.dll'; <br><br>-- Add the REGEX function. We want a friendly name <br>-- RegExMatch rather than the full namespace name. <br>-- Note the way we have to specify the Assembly.Namespace.Class.Function <br>-- NOTE the RegExCLR.RegExCLR <br>-- (one is the assembly the other is the namespace) <br>CREATE FUNCTION RegExMatch ( @inputCalue NVARCHAR(4000), <br>@regexPattern NVARCHAR(4000) ) RETURNS BIT <br>AS EXTERNAL NAME RegExCLR.RegExCLR.ClrClass.RegExMatch; <br> <br>OK, 一切OK的后,我们来测试下: <br><br>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 <br>上面的T-SQL是找出Threads表ThreadId是GUID的记录数。 等于1是匹配,^[{|\(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[\)|}]?$ 匹配GUID的正则表达式。 <br><br>完了,希望这篇POST对您有帮助。<br><br>您可能对以下POST感兴趣: </li></ol></pre>