[英]SQL Like vs C# Contains difference
I have following SQL in C#, 我在C#中使用了以下SQL,
var str= QueryExecutor.Query<string>("SELECT SomeColumn from Somtable WHERE SomeColumn LIKE '%abc_def%'", new { }, CommandType.Text).FirstOrDefault();
if (str.Contains("abc_def"))
{
}
Now I get the big string but str.Contains("abc_def")
returns false. 现在我得到了大字符串,但是str.Contains("abc_def")
返回false。 The column is NVARCHAR(MAX). 该列为NVARCHAR(MAX)。 Why contains and LIKE differ? 为什么包含和LIKE不同?
You are probably missing that _
is a wildcard for SQL LIKE
that matches exactly one character. 您可能会错过_
是SQL LIKE
的通配符,它恰好匹配一个字符。
So, LIKE '%abc_def%'
can match any character between the two: 因此, LIKE '%abc_def%'
可以匹配两者之间的任何字符:
abc1def
abcZdef
abc&def
abc_def
To match an underscore in SQL Server using LIKE
, you can use one of the following: 要使用LIKE
匹配SQL Server中的下划线,可以使用以下选项之一:
SomeColumn LIKE '%abc[_]def%' -- use a character class
SomeColumn LIKE '%abc$_def%' ESCAPE '$' -- use an escape character
Or, you can use charindex()
: 或者,您可以使用charindex()
:
CHARINDEX('abc_def', SomeColumn) > 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.