You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Implementing Regular Expressions in SQL Server using CLR UDF
2
+
SQL Database don't have built-in support for regular expressions, so the only workaround is to use Regular Expressions that exist in .Net framework and expose them as T-SQL functions.
3
+
This code sample demonstrates how to create CLR User-Defined functions that expose regular expression functionalities that exist in .Net framework.
4
+
5
+
### Contents
6
+
7
+
[About this sample](#about-this-sample)<br/>
8
+
[Build the CLR/RegEx functions](#build-functions)<br/>
9
+
[Add RegEx functions to your SQL database](#add-functions)<br/>
1. Download the source code and open the solution using Visual Studio.
27
+
2. Change the password in .pfk file and rebuild the solution in Retail mode.
28
+
3. Open and save SqlClrRegEx.tt to generate output T-SQL file that will contain script that inserts .dll file with the Regex functions, and exposes them as T-SQL/CLR functions.
29
+
30
+
<aname=add-functions></a>
31
+
## Add RegEx functions to your SQL database
32
+
33
+
File SqlClrRegEx.sql contains the code that will import functions into SQL Database.
34
+
35
+
If you have not added CLR assemblies in your database, you should use the following script to enable CLR:
Once you enable CLR, you can use the T-SQL script to add the regex functions. The script depends on the location where you have built the project, and might look like:
44
+
```
45
+
--Create the assembly
46
+
CREATE ASSEMBLY SqlClrRegEx FROM 'D:\GitHub\sql-server-samples\samples\features\sql-clr\RegEx\bin\Release\SqlClrRegEx.dll' WITH PERMISSION_SET = SAFE
47
+
GO
48
+
49
+
CREATE SCHEMA REGEX;
50
+
GO
51
+
52
+
--Create the functions
53
+
CREATE FUNCTION REGEX.MATCH (@src NVARCHAR(MAX), @regex NVARCHAR(4000))
54
+
RETURNS BIT
55
+
AS EXTERNAL NAME SqlClrRegEx.RegEx.CompiledMatch
56
+
GO
57
+
CREATE FUNCTION REGEX.SUBSTRING (@src NVARCHAR(MAX), @regex NVARCHAR(4000))
58
+
RETURNS NVARCHAR(4000)
59
+
AS EXTERNAL NAME SqlClrRegEx.RegEx.CompiledSubstring
60
+
GO
61
+
CREATE FUNCTION REGEX.REPLACE (@src NVARCHAR(MAX), @regex NVARCHAR(MAX), @value NVARCHAR(4000))
62
+
RETURNS NVARCHAR(MAX)
63
+
AS EXTERNAL NAME SqlClrRegEx.RegEx.CompiledReplace
64
+
GO
65
+
```
66
+
67
+
This code will import assembly in SQL Database and add three functions that provide RegEx functionalities.
68
+
69
+
<aname=test></a>
70
+
71
+
## Test the functions
72
+
73
+
Once you create the assembly and expose the functions, you can use regular expression functionalities in T-SQL code:
The code included in this sample is not intended to be a set of best practices on how to build scalable enterprise grade applications. This is beyond the scope of this sample.
0 commit comments