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.
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:
NULL
s appropriately @StartAt
, @RegExOptions
for IgnoreCase , MultiLine , etc) 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.