sql - 检查是否在 SQL 的多个列之一中找到字符串
问题描述
我想在多个列中搜索一个字符串以检查它是否存在于任何列中。我在这里找到了解决方案Thorsten
的答案很简短,但这是针对 mysql 服务器而不是针对 SQL Server 的解决方案。所以我想在 SQL Server 中应用类似的查询。
这是 Thorsten 建议的查询。
Select *
from tblClients
WHERE name || surname LIKE '%john%'
我试过了
/* This returns nothing */
Select *
from Items
Where ISNULL(Code, '') + ISNULL(Code1, '') = '6922896068701';
Go
/* This generate error Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '|'.
I also used this one in mysql but it does not show the exact match.
*/
Select *
from Items
WHERE Code || Code1 = '6922896068701';
Go
/* This generate error Msg 4145, Level 15, State 1, Line 5
An expression of non-boolean type specified in a context where a condition is expected, near 'Or'. */
Select *
from Items
WHERE Code Or Code1 = '6922896068701';
Go
在 SQL Server 中真的有可能吗?
注意:J__的答案在上面的问题链接中准确无误,但我希望为我查找它的所有列输入一次比较字符串,例如 Thorsten。
解决方案
实际上,我认为在WHERE
每个列的子句中进行单独的逻辑检查是要走的路。如果由于某种原因您不能这样做,请考虑使用WHERE IN (...)
子句:
SELECT *
FROM Items
WHERE '6922896068701' IN (Code, Code1);
相反,如果您想要LIKE
逻辑,那么它会变得很棘手。如果您知道匹配代码总是由数字/字母组成,那么您可以尝试:
SELECT *
FROM Items
WHERE ',' + Code + ',' + Code1 + ',' LIKE '%,6922896068701,%';