• 在TSQL中使用正则表达式函数


         有想过在T-Sql使用正则表达式吗?是的,完全可以的,我们可以用SQL SERVER CLR sql function来实现这一功能。
         首先,我们在VSTS中创建一Database Project,增一个class, 实现下面的一个方法:

       1:        /// <summary>
       2:        /// Regs the ex match.
       3:        /// </summary>
       4:        /// <param name="inputValue">The input value.</param>
       5:        /// <param name="regexPattern">The regex pattern.</param>
       6:        /// <remarks>Author: Petter Liu http://wintersun.cnblogs.com </remarks>
       7:        /// <returns>1 match,0 not match</returns>
       8:        [SqlFunction]
       9:        public static bool RegExMatch(string inputValue, string regexPattern)
      10:        {
      11:            // Any nulls - we can't match, return false
      12:            if (string.IsNullOrEmpty(inputValue) || string.IsNullOrEmpty(regexPattern))
      13:                return false;
      14:   
      15:            Regex r1 = new Regex(regexPattern.TrimEnd(null));
      16:            return r1.Match(inputValue.TrimEnd(null)).Success;
      17:        }

         好了,Build后Deploy到你的Target database就OK了,VisualStudio会自动注册这个程序集的。如果,你想手动注册程序集,可执行以下的T-SQL:

       1:  CREATE ASSEMBLY [RegExCLR] FROM 'RegExCLR.dll';
       2:   
       3:  -- Add the REGEX function.  We want a friendly name 
       4:  -- RegExMatch rather than the full namespace name.
       5:  -- Note the way we have to specify the Assembly.Namespace.Class.Function
       6:  -- NOTE the RegExCLR.RegExCLR 
       7:  -- (one is the assembly the other is the namespace)
       8:  CREATE FUNCTION RegExMatch ( @inputCalue NVARCHAR(4000), 
       9:      @regexPattern NVARCHAR(4000) ) RETURNS BIT
      10:      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


    作者:Petter Liu
    出处:http://www.cnblogs.com/wintersun/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    该文章也同时发布在我的独立博客中-Petter Liu Blog

  • 相关阅读:
    前端之HTML
    python 迭代器、生成器、装饰器
    python实现线程池
    Archiva与maven配置使用
    Jenkins在windows环境下安装无法安装插件
    ②Jenkins集成—集成构建部署
    linux环境下maven的安装配置
    linux环境下git的安装配置
    ①Jenkins集成—入门安装使用
    Ant build.xml相关属性详解
  • 原文地址:https://www.cnblogs.com/wintersun/p/1765383.html
Copyright © 2020-2023  润新知