简体   繁体   English

使用条件案例语句的SQL搜索

[英]SQL search using condition in case statement

I need to perform a search based on condition. 我需要根据条件进行搜索。 If I pass @SearchCondition = 1 then the search should be performed on OrderId column for the passed @SearchValue If I pass @SearchCondition = 0 the search must return all the records minus the record with @SearchValue 如果我通过@SearchCondition = 1,则应该在传递的@SearchValue的OrderId列上执行搜索。如果我通过@SearchCondition = 0,则搜索必须返回减去@SearchValue的所有记录。

IF @SearchCondition = 1 
   Search Records With [OrderId] = @SearchValue

IF @SearchCondition = 0 
   Get All The Records With [OrderId] <> @SearchValue

But the above needs to be done in a single statement (ideally CASE statement). 但是上述操作需要在单个语句(理想CASE下为CASE语句)中完成。 No IF-ELSE since the query is too big and I do not want to write the same long query twice but with only a single different line. 没有IF-ELSE因为查询太大,我不想两次写相同的长查询,而只用一行不同。 Here is the sample table for convenience: 为方便起见,这是示例表:

DECLARE @SearchCondition INT = 0, @SearchValue INT = 121 
CREATE TABLE #TempData
(
[Id] INT IDENTITY(1,1),
[OrderId] INT,
[OrderName] VARCHAR(20)
)
INSERT INTO #TempData
SELECT 121, 'A1' UNION
SELECT 122, 'A2' UNION
SELECT 123, 'A3' UNION
SELECT 124, 'A4' UNION
SELECT 125, 'A5' UNION
SELECT 126, 'A6' UNION
SELECT 127, 'A7' UNION
SELECT 128, 'A8' UNION
SELECT 129, 'A9' UNION
SELECT 130, 'A10'   

--If SearchCondition = 1
SELECT [Id], [OrderId], [OrderName] 
FROM #TempData
WHERE [OrderId] = @SearchValue--If SearchCondition = 1
-- Handle If SearchCondition = 0
--SELECT [Id], [OrderId], [OrderName] 
--FROM #TempData
--WHERE [OrderId] <> @SearchValue

DROP TABLE #TempData

Need to merge the above statements in a single statement 需要将以上语句合并为一个语句

This is called a Catch-all Query . 这称为Catch-all Query One way is to use AND-OR combinations 一种方法是使用AND-OR组合

SELECT [Id], [OrderId], [OrderName] 
FROM #TempData
WHERE 
    (@SearchCondition = 1 AND [OrderId] = @SearchValue)
    OR (@SearchCondition = 0 AND [OrderId] <> @SearchValue)

Additional Reading: 补充阅读:

WHERE ([OrderId] = 
case when  @SearchCondition=1 then @SearchValue  end)
or ([OrderId] <>
case when  @SearchCondition=0 then @SearchValue  end)

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

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