简体   繁体   中英

Case Statement in 'IN' clause in SQL

I am trying to write a case statement inside the IN clause.

The Channel column contains three values ACT, REN, REP. I want to select more than 1 values, but I get result with only one value.

    select * from tbl
    WHERE tbl.Channel IN (select 
                                    case when @ACT =1 then 'ACT'
                                    when @REN =1 then 'REN' 
                                    when @REP =1 then 'REP' END)

What changes should I be doing here ?

Don't end your case. You are returning 3 columns. You only want one.

select * from tbl
    WHERE tbl.Channel =  case when @ACT =1 then 'ACT' 
                              when @REN =1 then 'REN'
                              when @REP =1 then 'REP' 
                              else NULL END

This will work fine. SQL Fiddle

The only change is removing the select so the input to the in clause is 3 values rather than a single row with three columns.

The implicit else null if the variable is not 1 does not cause a problem in an in clause.

SELECT * 
FROM   tbl 
WHERE  tbl.channel IN ( CASE 
                          WHEN @ACT = 1 THEN 'ACT' 
                        END, CASE 
                          WHEN @REN = 1 THEN 'REN' 
                        END, CASE 
                               WHEN @REP = 1 THEN 'REP' 
                             END ) 

You can write the clause without a case at all:

select *
from tbl
where (tbl.Channel 'ACT' and @ACT = 1) or
      (tbl.Channel = 'REN' and @REN = 1) or
      (tble.Channel = 'REP' and @REP = 1);

Your select statement is not correct and should return an error. select statements in in clauses are not allowed to return more than one column.

Here is an alternative that should let you perform the selection without an IN operator:

select * from tbl
WHERE (tbl.Channel='ACT' AND @ACT=1)
   OR (tbl.Channel='REN' AND @REN=1)
   OR (tbl.Channel='REP' AND @REP=-1)

If you must use IN operator, you should be able to construct a query with UNION ALL , like this:

select * from tbl
WHERE tbl.Channel IN (
    select case when @ACT =1 then 'ACT' END FROM DUAL
        UNION ALL
    select case when @REN =1 then 'REN' END FROM DUAL
        UNION ALL
    select case when @REP =1 then 'REP' END FROM DUAL)

Demo.

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