以下例子演示整个实现过程:
1、新建一个类库程序命名为Regex,打开Visual Studio 2008,点击File,点击New,点击Project,在弹出的New Project对话框中选择Class Library,项目名称为Regex。
2、将项目中的类Class1命名为Regex,在这个类中写入如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;
namespace RegExp
{
publicpartialclass RegExp
{
[SqlFunction(IsDeterministic =true, DataAccess = DataAccessKind.None)]
publicstatic SqlString RegexReplace(
SqlString input, SqlString pattern, SqlString replacement)
{
return (SqlString)Regex.Replace(
input.Value, pattern.Value, replacement.Value);
}
}
}
这个类中使用System.Text.RegularExpressions.Regex类中的Replace函数,这个在C#是常用的一个函数,使用正则表达式实现替换功能。编译这个类库项目生成RegExp.dll,这个在后面会用到的。
3、下面打开SQL Server 2008的管理界面,我们需要把这个dll部署到数据库中,然后再注册一个方法,但是在这之前需要在SQL Server中开启CLR调用功能,运行下面的SQL 语句:
exec sp_configure 'clr enabled', 1;
reconfigure;
4、运行下面的语句从这个dll中抽取中间语言(IL),如果你自己试验,注意修改dll文件存放路径。
use AdventureWorks;
create assembly RegExp from'D:\MyProject\RegExp\RegExp\bin\Debug\RegExp.dll'
这个时候我们就可以在SQL Server中查看这个集合了,点击展开数据库AdventureWorks,点击展开Programmability,点击展开Assemblies就可以看到Regex,如下图1。

图1
5、再写一个SQL函数来注册这个Assembly,代码如下
create function dbo.RegexReplace(
@input as nvarchar(max),
@pattern as nvarchar(max),
@replacement as nvarchar(max))
returns nvarchar(max) with returns null on null input
external name [RegExp].[RegExp.RegExp].[RegexReplace]
go
注意:
a.with returns null on null input意思是只要调用函数的时候任何一个参数为null,函数返回值将会是null。
b. 最后一句引用类库的格式需要写成[MyAssemblyName]. [MyAssemblyName.MyClassName].[MyMethodName]
调用示例:
将China中的字母a替换成z
select dbo.RegexReplace('china','a','Z')
本文介绍如何在SQL数据处理中使用T-SQL完成大部分操作,并通过集成外部dll实现特定功能,如磁盘文件序列化、正则表达式文本替换等。详细步骤包括创建类库、部署dll至数据库、注册方法并提供示例调用。
5694

被折叠的 条评论
为什么被折叠?



