使用.net類庫向sql server中添加正則表達式

構建類庫

  1. 創建.net類庫
  2. 創建正則比較方法
namespace SqlServerRegex
{
    public class RegexExtend
    {
        [Microsoft.SqlServer.Server.SqlFunction]
        public static bool IsMatch(string regex, string input)
        {
            return !string.IsNullOrEmpty(input) && new Regex(regex).IsMatch(input);
        }
    }
}
  1. rebuild項目

添加到Sql Server

--使數據庫受到信任
ALTER DATABASE TestDatabase set TRUSTWORTHY ON;
--註冊.net類庫,unsafe 不受限制地訪問資源
CREATE ASSEMBLY Regex from 'C:\Project\SqlServerRegex\bin\Debug\SqlServerRegex.dll' WITH PERMISSION_SET = UnSafe; 
--將數據庫設置爲可以使用clr組件
sp_configure 'clr enabled', 1;
--設置可用clr組件。別忘記運行這行進行應用
RECONFIGURE;
--創建函數
CREATE FUNCTION [dbo].[Regex.IsMatch](@Regex [nvarchar](max),@Input [nvarchar](max))
RETURNS [bit] WITH EXECUTE AS CALLER
AS 
EXTERNAL NAME [Regex].[SqlServerRegex.RegexExtend].[IsMatch];

微軟官方文檔

測試

SELECT *
 FROM dbo.TestRegex
where dbo.[Regex.IsMatch]('\d+',code)!=0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章