Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'])."$'
like image 671
dbomb101 Avatar asked Mar 25 '10 12:03

dbomb101


People also ask

Does SQL Server have RegEx?

Unlike MySQL and Oracle, SQL Server databases don't support built-in RegEx functions. However, SQL Server offers the following built-in functions to tackle such complex issues: LIKE. PATINDEX.

Can we use REGEXP in MySQL?

MySQL supports another type of pattern matching operation based on the regular expressions and the REGEXP operator. It provide a powerful and flexible pattern match that can help us implement power search utilities for our database systems. REGEXP is the operator used when performing regular expression pattern matches.

What is RegEx SQL Server?

Regular expressions are a concise and flexible notation for finding and replacing patterns of text. A specific set of regular expressions can be used in the Find what field of the SQL Server Management Studio Find and Replace dialog box.

Can you use RegEx in SSMS?

In tools, such as SSMS, you can specify the regex patterns in the Find What and Find and Replace options.


1 Answers

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;
  }
}
like image 121
leppie Avatar answered Nov 02 '22 12:11

leppie