简体   繁体   中英

Case statement inside IN statement

I have a variable age to be used on my query like below:

Declare @age as int 11

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

but I want to show all the people between 10 and 13 when I put 0 on @age, so I'm trying to do something like this:

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

Can someone give me a light?

You do not need a CASE statement, you can just switch your WHERE clause around a bit. This should return the same results:

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

You don't need a case statement:

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)

This seems easiest

It is also easy to modify if the business rules change.

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
select *
from people
where (age between 10 and 13 and @age=0) 
or (age = @age)

you need to add the SELECT to your IN() part

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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