原文:https://www.jianshu.com/p/ff16a7da6de0
1、vs添加類庫,編寫如下代碼,生成dll

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Text.RegularExpressions; 6 using System.Threading.Tasks; 7 8 namespace MSSQLRegexExtend 9 { 10 public class RegexExtend 11 { 12 /// <summary> 13 /// 正則匹配 14 /// </summary> 15 /// <param name="regex">正則表達式</param> 16 /// <param name="input">文本</param> 17 /// <returns></returns> 18 [Microsoft.SqlServer.Server.SqlFunction] 19 public static string Match(string regex, string input) 20 { 21 return string.IsNullOrEmpty(input) ? "" : new Regex(regex, RegexOptions.IgnoreCase).Match(input).Value; 22 } 23 24 /// <summary> 25 /// 正則替換 26 /// </summary> 27 /// <param name="regex">正則表達式</param> 28 /// <param name="input">文本</param> 29 /// <param name="replace">要替換的目標</param> 30 /// <returns></returns> 31 [Microsoft.SqlServer.Server.SqlFunction] 32 public static string Replace(string regex, string input, string replace) 33 { 34 return string.IsNullOrEmpty(input) ? "" : new Regex(regex, RegexOptions.IgnoreCase).Replace(input, replace); 35 } 36 37 /// <summary> 38 /// 正則校驗 39 /// </summary> 40 /// <param name="regex">正則表達式</param> 41 /// <param name="input">文本</param> 42 /// <returns></returns> 43 [Microsoft.SqlServer.Server.SqlFunction] 44 public static bool IsMatch(string regex, string input) 45 { 46 return !string.IsNullOrEmpty(input) && new Regex(regex, RegexOptions.IgnoreCase).IsMatch(input); 47 } 48 } 49 }
2、sqlserver中注冊此dll
1 /****注冊.net類庫****/ 2 use Northwind 3 --1.注冊.net類庫 4 CREATE ASSEMBLY Regex from 'dll的全路徑' WITH PERMISSION_SET = SAFE 5 6 --2.將數據庫設置為可以使用clr組件 7 sp_configure 'clr enabled', 1 8 9 --3.設置可用clr組件。別忘記運行這行進行應用 10 RECONFIGURE 11 12 --4.刪除該類庫(刪除時執行) 13 --DROP ASSEMBLY Regex
3、將dll中的方法注冊為sqlserver中的函數
1 /****以下代碼將類庫中的靜態方法注冊為函數****/ 2 --1.正則匹配 3 CREATE FUNCTION [dbo].[Regex.Match](@Regex [nvarchar](max),@Input [nvarchar](max)) 4 RETURNS [nvarchar](max) WITH EXECUTE AS CALLER 5 AS 6 EXTERNAL NAME [Regex].[MSSQLRegexExtend.RegexExtend].[Match] 7 8 --DROP FUNCTION [dbo].[Regex.Match] 9 10 --2.正則替換 11 CREATE FUNCTION [dbo].[Regex.Replace](@Regex [nvarchar](max),@Input [nvarchar](max),@Replace [nvarchar](max)) 12 RETURNS [nvarchar](max) WITH EXECUTE AS CALLER 13 AS 14 EXTERNAL NAME [Regex].[MSSQLRegexExtend.RegexExtend].[Replace] 15 16 --DROP FUNCTION [dbo].[Regex.Replace] 17 18 --3.正則校驗 19 CREATE FUNCTION [dbo].[Regex.IsMatch](@Regex [nvarchar](max),@Input [nvarchar](max)) 20 RETURNS [bit] WITH EXECUTE AS CALLER 21 AS 22 EXTERNAL NAME [Regex].[MSSQLRegexExtend.RegexExtend].[IsMatch]
此時就可以正常調用了