您的位置:首页 > 数据库

让正则表达式也加入你的Transaction-SQL吧!(CLR SQL SERVER)

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

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

程序代码

[csharp] view plain copy

print?

/*引用程序集*/

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<a href="http://lib.csdn.net/base/dotnet" class="replace_word" title=".NET知识库" target="_blank" style="color:#df3434; font-weight:bold;">.NET</a>/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>

}

代码分析

我们定义的这两个C#函数会映射为数据库的表值函数,该函数的具体思路是:通过正则表达式将一段字符内容进行分拆,分拆的过程有点象C#中我们用到的Split函数,但我们这里用的是正则来进行分拆,所以比它要强大。为了方便读取分拆后的结果,就将分拆的结果组织成结果集的形式进行返回。

部署步骤

[sql] view plain copy

print?

--在Sql Server中开启对程序集的信任

sp_configure [clr enabled],1 reconfigure

--注册程序集

create assembly Liby_SQL_CLR_FUNCTION from

'C:\CLR_FUNCTION\编译后生成的名称.dll'

--注册函数

create function SPLICT_STR_BY_REGEX_1(@input nvarchar(max),@pattern nvarchar(max)) returns table(tmp_value nvarchar(max))

as

external name 程序集名称.CLR_FUNCTION.[SPLICT_STR_BY_REGEX_1]

执行结果

[sql] view plain copy

print?

select * from SPLICT_STR_BY_REGEX_1('1,2,3,4,5,12','\d{1,2}')



小结

编程最重要的就是效率,详细把正则引进到数据库编程中会轻松的解决很多难题,希望这篇博文能对大家有所帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: