Welcome

首页 / 数据库 / SQLServer / CLR SQL SERVER:让正则表达式也加入你的Transaction-SQL

CLR SQL SERVER:让正则表达式也加入你的Transaction-SQL2013-12-09试过Transaction-Sql编程的哥们应该都觉的这东西太恶心了,除了IDE,最恶心得还数编程中涉及的字符 串拼接问题。想象一下:在一个巨复杂的业务逻辑中,里面充满了while,if,case。你必须处理好所有的情 况并按某一规则来拼接字符串。这些字符串可能是Sql,也可能是结果,但不管是什么都是我们的噩梦。

正则表达式是啥相信就不要我介绍了,处理文本的利器呀。虽然Sql Server也支持正则表达式,但使 用比较麻烦,还是自己制作一个正则表达函数来的方便。这节主要涉及了CLR Sql Server技术,该技术是从 Sql Server 2005时被提出来的,就目前来看是个比较成熟的技术。现在我们就来DIY自己的正则函数吧!

程序代码

/*引用程序集*/using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;using System.Text.RegularExpressions;using System.Xml.Linq;using System.Xml;using System.IO;using System.Collections;<p> public class CLR_FUNCTION{public CLR_FUNCTION() { } /// 作者:GhostBear/// 博客地址: http://blog.csdn.net/ghostbear/// 表值函数,通过正则表达式来将对象进行拆分()。拆分结果以行记录的形式输出。/// 例:/// 需要拆分的数据:1,2,3,4,5,12,8/// 进行拆分的正则表达式:d{1,2}/// 输出的结果:/// 1/// 2/// 3/// 4/// 5/// 12/// 8/// </summary>/// <param name="input">需要拆分的数据</param>/// <param name="pattern">用来拆分的正则表达式</param>/// <returns>拆分后的记录</returns>[SqlFunction(TableDefinition="tmp_value nvarchar(max)",FillRowMethodName="SplictByRegex_FillRow")]public static IEnumerable SPLICT_STR_BY_REGEX_1(SqlString input, SqlString pattern){IList<string> result2 = new List<string>();var matches = Regex.Matches(input.ToString().Trim(), pattern.ToString().Trim());</p><p>foreach (Match m in matches){if (m.Success){result2.Add(m.Value);}}</p><p>return result2.AsEnumerable();}</p><p>public static void SplictByRegex_FillRow(object obj, out SqlString tmp){tmp = new SqlString(obj.ToString());}</p>}