问题
Using SQL Server 2008 I'd like to run a regex on a DB value before comparing it.
I'm looking into CLR User-Defined Functions (I investigated EDM Functions but I got the impression that UDFs were more appropriate with a regex - please correct me if I'm wrong).
Ideally I'd like to make a linq call like this:
var results= db.Items.Where(i => i.CustomFormatFunction() == xyz);
So far I have this c# code:
public static partial class UserDefinedFunctions
{
[SqlFunction]
public static SqlString CustomFormatFunction(string str)
{
return Regex.Replace(Regex.Replace(HttpUtility.HtmlDecode(str), @"\s+", "-"), "[^a-zA-Z0-9/-]+", "").ToLower();
}
}
What further steps are required in order for me to be able to use it in a linq query?
回答1:
I actually coded up this exact function some time ago. Mine's a bit more general purpose, but it looks like this:
[SqlFunction(DataAccess = DataAccessKind.Read, IsDeterministic = true)]
public static string Replace(string input, string pattern, string replacement, int options)
{
return Regex.Replace(input, pattern, replacement, (RegexOptions)options);
}
You then have to register it in SQL with
CREATE ASSEMBLY [MyAssembly]
FROM 'C:\Path\To\Assembly\MyAssembly.dll'
WITH PERMISSION_SET = SAFE
GO
CREATE FUNCTION [dbo].[Replace](@input [nvarchar](4000), @pattern [nvarchar](4000), @replacement [nvarchar](4000), @options [int] = 0)
RETURNS [nvarchar](4000) NULL
WITH EXECUTE AS CALLER
AS EXTERNAL NAME [MyAssembly].[MyNamespace.UserDefinedFunctions].[Replace]
GO
That will create your CLR-UDF in SQL. I've never tried linking back to a linq query, but I assume it would work like any other EDM function.
[EdmFunction("dbo", "Replace")]
public static string Replace(Replace input, pattern, replace, int flags)
{
throw new NotSupportedException("Direct calls not supported");
}
You might even be able to put SqlFunction and EdmFunction attributes on the same method, but I don't recommend it (it also seems like pushing the limit of circularity). I prefer to keep my CLR-UDF functions in a completely separate assembly, since they change very infrequently and my assemblies which consume the data are very dynamic.
来源:https://stackoverflow.com/questions/15669956/how-to-register-clr-user-defined-function-for-use-in-linq-query