使用case语句中的条件进行SQL搜索

时间:2016-06-23 07:12:28

标签: sql sql-server

我需要根据条件进行搜索。如果我传递@SearchCondition = 1,则应在OrderId列上执行搜索以传递@SearchValue如果我传递@SearchCondition = 0,搜索必须返回所有记录减去记录@SearchValue

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

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

但上述内容需要在一个语句中完成(理想情况为CASE语句)。没有IF-ELSE,因为查询太大,我不想写两次相同的长查询,但只有一个不同的行。为方便起见,这是示例表:

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

需要在单个陈述中合并上述陈述

2 个答案:

答案 0 :(得分:7)

这称为Catch-all Query。一种方法是使用AND-OR组合

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

补充阅读:

答案 1 :(得分:0)

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