开发者

Microsoft SQL Server equivalent of MySQL REGEXP

开发者 https://www.devze.com 2022-12-24 20:04 出处:网络
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 l开发者_如何学编程ike 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 l开发者_如何学编程ike 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 NULLs appropriately
  • perform better / more efficient
  • have more options (e.g. @StartAt, @RegExOptions for IgnoreCase, MultiLine, etc)
  • provide more functionality (e.g. CaptureGroup, CaptureGroupCapture, Escape, Unescape, etc)
  • require no additional effort to deploy (i.e. 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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号