sqlserver 执行正则表达式,调用c# 函数、代码
发布时间:2020-12-12 13:03:15 所属栏目:MsSql教程 来源:网络整理
导读:--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
--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 */(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |