按一个属性过滤两列

时间:2019-12-09 11:02:45

标签: sql sql-server tsql

我有一个WHERE,看起来像这样:

SELECT * FROM Tasks t WHERE (@search IS NULL OR (t.TaskId LIKE '%' + @search + '%'))

此处即时搜索@search中与t.TaskId属性匹配的所有记录。

现在,我想做这样的事情:

SELECT * FROM Tasks t WHERE (@search IS NULL OR (t.TaskId LIKE '%' + @search + '%'))
                            AND (@search IS NULL OR (t.ProjectId LIKE '%' + @search + '%'))

我要搜索与@search匹配的记录,先检查TaskId,然后检查ProjectId,但目前无法正常工作。

如何通过一个属性过滤查询中的两列?

4 个答案:

答案 0 :(得分:2)

在这种情况下,索引将不会用于LIKE,因此您可以只使用COALESCE()

SELECT t.*
FROM Tasks t
WHERE t.TaskId LIKE '%' + COALESCE(@search, '') + '%') AND
      t.ProjectId LIKE '%' + COALESCE(@search, '') + '%');

或者等效地,您可以使用CONCAT()(在SQL Server中忽略NULL):

SELECT t.*
FROM Tasks t
WHERE t.TaskId LIKE CONCAT('%', @search, '%') AND
      t.ProjectId LIKE CONCAT('%', @search, '%');

答案 1 :(得分:1)

使用OR代替AND

SELECT * FROM Tasks t 
WHERE (@search IS NULL OR (t.TaskId LIKE '%' + @search + '%'))
   OR (@search IS NULL OR (t.ProjectId LIKE '%' + @search + '%'))
   ^^------------------here

或更短:

SELECT * FROM Tasks t 
WHERE @search IS NULL 
OR 
(
   t.TaskId LIKE '%' + @search + '%' OR
   t.ProjectId LIKE '%' + @search + '%'
)

答案 2 :(得分:1)

您可以执行以下操作。

 SELECT * FROM Tasks t WHERE @search IS NULL OR( t.TaskId LIKE '%' + @search + '%' and 
 t.ProjectId LIKE '%' + @search + '%')

答案 3 :(得分:1)

在通配符的前后,您可能要尝试使用IIF的PATINDEX:

SELECT * 
FROM Tasks t 
WHERE PATINDEX(IIF(@search IS NULL, '', '%' + @search + '%'), t.TaskId) > 0
OR PATINDEX(IIF(@search IS NULL, '', '%' + @search + '%'), t.ProjectId) > 0

或者,您也可以预先准备@search变量以使查询更简洁:

SET @search = IIF(@search IS NULL, '', '%' + @search + '%')

SELECT * 
FROM Tasks t 
WHERE PATINDEX(@search, t.TaskId) > 0
OR PATINDEX(@search, t.ProjectId) > 0

https://docs.microsoft.com/en-us/sql/t-sql/functions/patindex-transact-sql?view=sql-server-ver15

https://docs.microsoft.com/en-us/sql/t-sql/functions/logical-functions-iif-transact-sql?view=sql-server-ver15