在SQL Server 2005中使用正则表达式

2026-03-10 06:35 栏目: 知识在线 查看( )

CLR用户定义函数只是在.NET 程序集中定义的静态方法。CREATE FUNCTION 语句已扩展为支持创建 CLR 用户定义函数。

1、创建数据库项目

在SQL Server 2005中使用正则表达式(图1)

2、添加用户定义函数

在SQL Server 2005中使用正则表达式(图2)

以下是演示代码:

Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;

// 示意代码
public partial class UserDefinedFunctions
{
public static readonly RegexOptions Options =

RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline;

[Microsoft.SqlServer.Server.SqlFunction]
public static string RegexValue(SqlChars input, SqlString pattern)
{
Regex regex = new Regex(pattern.Value, Options);

return  regex.Match(new string(input.Value)).Value;
}
}

3、将自定义函数关联到数据库

在SQL Server 2005中使用正则表达式(图3)

4、Sql 查询分析器

在SQL Server 2005中使用正则表达式(图4)

为了确保SQL可以执行托管代码,执行下面的语句:

EXEC sp_configure 'clr enabled', 1

sql 如下:
select dbo.RegexValue('2008-09-02',N'd{4}') from Table

============================================= 

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流

郑重申明:某某网络以外的任何单位或个人,不得使用该案例作为工作成功展示!