1. 程式人生 > >sqlserver 運行正則表達式,調用c# 函數、代碼

sqlserver 運行正則表達式,調用c# 函數、代碼

exp pan net hit ng- 創建 val put creat



--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
*/

sqlserver 運行正則表達式,調用c# 函數、代碼