sqlserver 執行Regex,調用c# 函數、代碼

來源:互聯網
上載者:User

標籤: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# 函數、代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.