简体   繁体   中英

Microsoft SQL Server equivalent of MySQL REGEXP

I am trying to reconstruct a database query I created for MySQL in Microsoft SQL Server. I am looking for an operator or function SQL Server which acts like REGEXP .

Here is an example of how I am using the operator:

select *
from   musicdetails
WHERE  artistname REGEXP '^".mysql_escape_string($_GET['search'])."$'

Here you go (compile as SQL CLR assembly):

using System.Collections;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
  [SqlFunction]
  public static bool RegexMatch(string expr, string regex)
  {
    return Regex.IsMatch(expr, regex);
  }

  [SqlFunction]
  public static string RegexReplace(string expr, string regex, string replace)
  {
    return Regex.Replace(expr, regex, replace);
  }

  [SqlFunction(FillRowMethodName="GetToken", 
       TableDefinition="Value nvarchar(max)")]
  public static IEnumerable RegexSplit(string expr, string regex)
  {
    return Regex.Split(expr, regex);
  }

  public static void GetToken(object row, out string str)
  {
     str = (string) row;
  }
}

The only way you can do this in SQL Server (2005 and up only) is to use CLR functions; regular expressions as part of native SQL queries isn't standard.

http://msdn.microsoft.com/en-us/magazine/cc163473.aspx

While the code in leppie's answer will compile and execute, I would not recommend it for production use. If you want RegEx functions that:

  • are coded using best practices (for performance and security)
  • handle NULL s appropriately
  • perform better / more efficient
  • have more options (eg @StartAt , @RegExOptions for IgnoreCase , MultiLine , etc)
  • provide more functionality (eg CaptureGroup , CaptureGroupCapture , Escape , Unescape , etc)
  • require no additional effort to deploy (ie a single, self-contained T-SQL script that is portable and versionable, and installs cleanly with no need to manually enable "CLR enabled" or mess with the "CLR strict security" setting that was introduced in SQL Server 2017 )

and are also free, then check out the SQL# SQLCLR library (that I wrote). There are 13 RegEx functions in the Free version (and 2 more in the Full / paid version, plus the ability to increase the expression cache size, which can help if you frequently use a variety of expressions).

I believe the function RegEx_IsMatch (or RegEx_IsMatch4k ) is what you are looking for (yes, it is in the Free version).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM