我们平常在做字符串的模糊查询时,有可能会用到下面的类似LINQ写法:
string.IsNullOrEmpty(_SN) ? true : a.SN.IndexOf(_SN) != -1
这条LINQ翻译为SQL如下:
( ( 。
返回的开始位置从 1 开始,而非从 0 开始。
分析以下几种情况:
表达式2为空白值的情况
SELECT ( 为空值(NULL)的情况
SELECT ( CASE
WHEN ( ( '123456' IS NULL )
OR ( ( Cast(Len('123456') AS INT) ) = 0 ) ) THEN Cast(1 AS BIT)
WHEN ( NOT ( ( -1 = ( ( Cast(Charindex('123456', null) AS INT) ) - 1 ) )
AND ( ( Cast(Charindex('123456', null) AS INT) ) - 1 IS NOT NULL ) ) ) THEN Cast(1 AS BIT)
WHEN ( -1 = ( ( Cast(Charindex('123456', null) AS INT) ) - 1 ) ) THEN Cast(0 AS BIT)
END )
结果为1
测试其关键部分
SELECT ( CASE
WHEN ( NOT(( -1 = ( ( Cast(Charindex('123456', null) AS INT) ) - 1 ) )
AND ( ( Cast(Charindex('123456', null) AS INT) ) - 1 IS NOT NULL ) ) ) THEN Cast(1 AS BIT)
END )
结果为1
也就是说,当表中要查找的列中存在空值时,用indexOf会把所有空值列查出来。
其原因就是上文所说的黄色部分,注意那个NOT,它放错了位置!
正确方式如下:
SELECT ( CASE
WHEN ( ( '123456' IS NULL )
OR ( ( Cast(Len('123456') AS INT) ) = 0 ) ) THEN Cast(1 AS BIT)
WHEN ( ( NOT( -1 = ( ( Cast(Charindex('123456', null) AS INT) ) - 1 ) )
AND ( ( Cast(Charindex('123456', null) AS INT) ) - 1 IS NOT NULL ) ) ) THEN Cast(1 AS BIT)
WHEN ( -1 = ( ( Cast(Charindex('123456', null) AS INT) ) - 1 ) ) THEN Cast(0 AS BIT)
END )
结果为NULL
结论:
当我们在模糊查询时,如果确定要查的列没有NULL值,可以使用indexOf,否则要考虑其它方式,比如Contains(它翻译的SQL为LIKE)。