標籤:c# .net sqlserver
--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>
/// Regex
/// </summary>
/// <param name="input">輸入字元</param>
/// <param name="pattern">Regex</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 執行Regex,調用c# 函數、代碼