繁体   English   中英

如何使用正则表达式和linq与SQL进行字符串比较

[英]How to do a string compare using regex and linq to sql

以下代码因错误而失败:

LINQ to Entities does not recognize the method 'Boolean CompareNames(System.String, System.String)' method, and this method cannot be translated into a store expression.

我知道我的CompareNames方法无法转换为SQL语句,但想知道一种无需从数据库中提取整个表进行比较即可完成此任务的方法。

// Use my method in Linq to Sql lambda
Repo.Get<T>(c => CompareNames(c.Name, newName)).ToList()

// Compare two names removing spaces and non-numeric characters
private static bool CompareNames(string str1, string str2)
{
    str1 = Regex.Replace(str1.Trim(), "[^a-z,A-Z,0-9.]", "");
    str2 = Regex.Replace(str2.Trim(), "[^a-z,A-Z,0-9.]", "");

    return str1 == str2;
}

没有创建自定义SQL函数的简便方法。 此功能为您提供了一个不错的起点:

CREATE FUNCTION dbo.udf_GetNumeric
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
    DECLARE @intAlpha INT
    SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
    BEGIN
        WHILE @intAlpha > 0
        BEGIN
            SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
            SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
        END
    END
    RETURN ISNULL(@strAlphaNumeric,0)
END
GO

https://blog.sqlauthority.com/2008/10/14/sql-server-get-numeric-value-from-alpha-numeric-string-udf-for-get-numeric-numbers-only/

只需使用兼容的like语句替换函数中的模式:

'%[^A-Za-z0-9.,]%'

您可以从LINQ到SQL调用用户定义的函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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