sqlserver 运行正則表達式,调用c# 函数、代码



--1.新建SqlServerExt项目,编写 C# 方法生成 SqlServerExt.dll 文件
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;


namespace Ext
{
    public static partial class DataBase
    {
        /// <summary>
        /// 正則表達式
        /// </summary>
        /// <param name="input">输入字符</param>
        /// <param name="pattern">正則表達式</param>
        /// <returns></returns>
        [Microsoft.SqlServer.Server.SqlFunction]
        public static SqlBoolean Regex(SqlChars input, SqlString pattern)
        {
            try
            {
                Regex regex = new Regex(pattern.Value);
                return new SqlBoolean(regex.IsMatch(new string(input.Value)));
            }
            catch
            {
                return new SqlBoolean(false);
            }
        }
    }
}


--2.在SqlServer 中注冊程序集
CREATE ASSEMBLY Udf 
FROM 'D:.......SqlServerExt.dll'

WITH PERMISSION_SET = SAFE;

--2.1 删除已注冊的程序集 Udf
--DROP ASSEMBLY Udf;


--3.创建一个sql 函数
CREATE FUNCTION Regex
(
@input NVARCHAR(4000) ,
@pattern nvarchar(4000)

RETURNS bit
AS
EXTERNAL NAME [Udf].[Ext.DataBase].[Regex] ;
--EXTERNAL NAME [Sql中程序集名].[C#命名空间.C#类名].[C#方法名]

--3.1 删除函数
--DROP FUNCTION Regex;


--4.測试正则
--4.1 匹配全部数字
select dbo.regex('123asd123','^d+$');
select dbo.regex('123000123','^d+$');
--4.2 查询mytable表中mycol字段中,包括全部数字的记录
select top 10 * from [mytable] where dbo.regex([mycol],'^d+$');




--5.运行 自己定义函数异常时
--消息 6263。级别 16,状态 1,第 2 行
--禁止在 .NET Framework 中运行用户代码。启用 "clr enabled" 配置选项。
/*
--出现例如以下提示时,运行下方代码
--消息 6263,级别 16,状态 1,第 2 行
--禁止在 .NET Framework 中运行用户代码。启用 "clr enabled" 配置选项。


exec sp_configure 'show advanced options', '1';
go
reconfigure;
go
exec sp_configure 'clr enabled', '1'
go
reconfigure;
exec sp_configure 'show advanced options', '1';
go
*/
原文地址:https://www.cnblogs.com/gccbuaa/p/6995083.html