試過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>
}