Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Server REGEXP_LIKE: How to Use It

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

SQL Server does not have a built-in REGEXP_LIKE function. To use regular expressions in SQL Server, you must enable and use SQL Server's CLR integration with a custom function or use the LIKE operator with limited pattern matching. The most practical approach is to create a CLR function that wraps .NET's Regex class, then call it from T-SQL. This guide walks you through enabling CLR, deploying a regex function, and using it safely.

What You'll Need

  • SQL Server 2017 or later (CLR integration is available in all editions, but enabling it requires sysadmin or server-level permissions).
  • Permission to run sp_configure and RECONFIGURE (typically sysadmin).
  • Visual Studio with SQL Server Data Tools (SSDT) or the .NET Framework (C# compiler) to build the CLR assembly. Alternatively, you can use a precompiled assembly if you have one.
  • Ability to set the database to TRUSTWORTHY ON or sign the assembly with a certificate (for safety, signing is preferred).
  • Basic familiarity with T-SQL and C# (or VB.NET).

Step-by-Step

  1. Enable CLR integration on the server. Connect to SQL Server Management Studio (SSMS) as a sysadmin. Run:
    sp_configure 'clr enabled', 1;
    RECONFIGURE;
    This enables the CLR runtime. You may need to restart SQL Server for the change to take effect, though RECONFIGURE usually suffices.
  2. Create a .NET assembly with a regex function. In Visual Studio, create a Class Library (.NET Framework) project targeting .NET Framework 4.6.2 or later (match your SQL Server version). Add a public static method that takes a string input and a pattern, and returns a bit (1 or 0). Example C# code:
    using System.Data.SqlTypes;
    using System.Text.RegularExpressions;
    public partial class RegexFunctions
    {
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlBoolean RegexIsMatch(SqlString input, SqlString pattern)
    {
    if (input.IsNull || pattern.IsNull) return SqlBoolean.Null;
    return new SqlBoolean(Regex.IsMatch(input.Value, pattern.Value));
    }
    }
    Build the project to produce a DLL.
  3. Deploy the assembly to SQL Server. In SSMS, connect to your database. Run:
    CREATE ASSEMBLY RegexFunctions FROM 'C:\path\to\YourAssembly.dll' WITH PERMISSION_SET = SAFE;
    If the assembly requires external access (unlikely for regex), use EXTERNAL_ACCESS instead, but SAFE is sufficient for pure regex. Note: If the database is not trustworthy, you may need to sign the assembly with a certificate and create a login from the certificate, then grant EXTERNAL ACCESS ASSEMBLY to that login. For simplicity, you can set the database TRUSTWORTHY ON, but that is a security risk; signing is recommended.
  4. Create a T-SQL function that calls the CLR method. Run:
    CREATE FUNCTION dbo.RegexIsMatch(@input NVARCHAR(MAX), @pattern NVARCHAR(MAX))
    RETURNS BIT
    AS EXTERNAL NAME RegexFunctions.RegexFunctions.RegexIsMatch;
    The EXTERNAL NAME format is AssemblyName.ClassName.MethodName. Adjust if your namespace or class differs.
  5. Test the function. Run a simple query:
    SELECT dbo.RegexIsMatch('abc123', '\d+') AS IsMatch;
    This should return 1. If it returns 0, check the pattern escaping (in T-SQL, backslashes are literal, so use '\d+' as shown).
  6. Use the function in queries. You can now use it in WHERE clauses, for example:
    SELECT * FROM Users WHERE dbo.RegexIsMatch(Email, '^[\w.-]+@[\w.-]+\.\w{2,}$') = 1;
    This filters rows where the Email column matches a basic email pattern. Remember that CLR functions can be slower than native predicates, so use them on small result sets or with indexes on other columns.
  7. Consider alternatives for simple patterns. For basic wildcard matching, use the LIKE operator (e.g., WHERE Email LIKE '%@%.%'). For more complex patterns, the CLR function is appropriate. SQL Server 2022 does not include a native REGEXP_LIKE; the CLR approach remains the standard workaround.

Common Mistakes

  • Forgetting to enable CLR. If you skip sp_configure 'clr enabled', 1, you'll get an error when creating the assembly.
  • Using the wrong permission set. SAFE is enough for regex; using EXTERNAL_ACCESS unnecessarily increases risk and may require additional configuration.
  • Incorrect EXTERNAL NAME. The three-part name must match the assembly name, fully qualified class name (including namespace), and method name exactly.
  • Not escaping backslashes in patterns. In T-SQL string literals, backslash is not an escape character, so '\d' is correct for a digit pattern. However, if you use parameters, the value is passed as-is.
  • Assuming REGEXP_LIKE exists. Many developers expect a built-in function like Oracle's; SQL Server does not have one, so you must implement it.
  • Ignoring performance. CLR functions are row-by-row and can be slow on large tables. Use them sparingly or pre-filter with native predicates.

Tips

  • Use WITH PERMISSION_SET = SAFE and sign the assembly with a certificate for production environments to avoid setting the database TRUSTWORTHY.
  • Test your regex patterns with a .NET regex tester before deploying to avoid surprises.
  • Consider creating a scalar function that returns the matched value or a table-valued function for more complex extraction, but start with a simple boolean match.
  • If you only need simple pattern matching, use LIKE with wildcards; it's faster and requires no CLR.
  • Document the function and its usage for your team, as CLR integration may be restricted in some environments.

Troubleshooting

If you encounter errors, check these common issues:

  • "CLR integration is disabled": Run sp_configure 'clr enabled', 1; RECONFIGURE; and restart SQL Server if needed.
  • "Assembly not found" or "Could not load file": Ensure the path to the DLL is correct and accessible by the SQL Server service account. Copy the DLL to a local drive on the server.
  • "CREATE ASSEMBLY failed because assembly is not trusted": Either set the database TRUSTWORTHY ON (not recommended) or sign the assembly with a certificate and create a login from the certificate, then grant EXTERNAL ACCESS ASSEMBLY to that login. For SAFE assemblies, trust is not required if the assembly is in the global assembly cache (GAC) or if the database is trustworthy; but typically, you need to sign.
  • Function returns NULL unexpectedly: Check that input and pattern are not NULL. The CLR method returns NULL if either is NULL.
  • Pattern not matching as expected: Remember that .NET regex is case-sensitive by default. Use the inline option (?i) for case-insensitive matching, e.g., (?i)abc.
  • Performance is poor: Avoid using the function in WHERE clauses on large tables without other filters. Consider computed columns with indexes if the pattern is fixed.

Frequently Asked Questions

Does SQL Server have a native REGEXP_LIKE function?

No. SQL Server does not include a built-in REGEXP_LIKE function. You must use CLR integration or the LIKE operator for pattern matching.

Can I use regular expressions without CLR?

Only limited pattern matching with LIKE (%, _, [], [^]) is available natively. For full regex, CLR is required.

Is enabling CLR safe?

CLR integration is safe when used with SAFE permission sets and signed assemblies. Avoid EXTERNAL_ACCESS unless necessary, and never set TRUSTWORTHY ON in production.

What .NET Framework version should I target?

Match the .NET Framework version supported by your SQL Server version. For SQL Server 2017 and later, .NET Framework 4.6.2 or later is recommended. Check Microsoft documentation for compatibility.

Can I use this function in a WHERE clause?

Yes, but be aware of performance implications. It is best used on small result sets or with other filtering conditions.

How do I handle case-insensitive matching?

Use the inline regex option (?i) at the start of your pattern, e.g., (?i)abc matches ABC, abc, etc.