IN语句中的case语句

时间:2012-08-13 19:49:51

标签: sql sql-server

我有一个可变年龄用于我的查询,如下所示:

Declare @age as int 11

Select * from people p where p.age = @age

但是当我把0放在@age上时,我想向10到13岁之间的所有人展示,所以我试图做这样的事情:

Select * 
from people p 
where p.age in( case 
                     when @age = 0 
                          then 10, 11, 12, 13
                          else @age
                     end
              )

有人可以给我一个灯吗?

5 个答案:

答案 0 :(得分:3)

您不需要CASE语句,只需稍稍切换WHERE子句即可。这应该返回相同的结果:

Select * 
from people p 
where 
( 
    @age = 0 
    AND p.age IN (10, 11, 12, 13)
)
OR
(
    @age != 0 
    AND p.age = @age
)

答案 1 :(得分:3)

您不需要案例陈述:

SELECT col1, col2, ..., coln
FROM people AS p 
WHERE (@age = 0 AND p.age BETWEEN 10 AND 13)
OR (@age <> 0 AND p.age = @age)

答案 2 :(得分:1)

这似乎最简单

如果业务规则发生变化,也很容易修改。

declare @min int
declare @max int
declare @age int

set @age = 0

if (@age = 0)
begin
   SET @min = 10
   SET @max = 13
end
else
begin
   SET @min = @age
   SET @max = @age
end 

Select * 
from people p 
where age >= @min and age <= @max

答案 3 :(得分:0)

select *
from people
where (age between 10 and 13 and @age=0) 
or (age = @age)

答案 4 :(得分:-2)

您需要将SELECT添加到IN()部分

Select * 
from people p 
where p.age in (SELECT case 
                     when @age = 0 
                          then 10, 11, 12, 13
                          else @age
                     end
              )