Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Multiple conditions in Case Statement

I have implemented multiple conditions in case statement as below,

select officied from budgettable
where budgetid = case @budgetid when 7 then 7
                when 7 then  8
                when 7 then 10
                when 8 then 6
          end

but it didn't give me any result. If I pass budget-Id as 7 the query should return 8,10,7 budget id's. Anything wrong in the above query?

like image 704
bmsqldev Avatar asked Dec 17 '25 20:12

bmsqldev


2 Answers

I suspect that you want something like this:

where budgetid = @budgetid or
      (@budgetid = 7 and budgetid in (7, 8, 10)) or
      (@budgetid = 8 and budgetid = 6)

Your query is failing because for all values of @budgetid other than 7 or 8, the case returns NULL -- which is treated as false.

like image 161
Gordon Linoff Avatar answered Dec 20 '25 13:12

Gordon Linoff


One option is to use the case as a boolean expression, returning 1 when your conditions are met:

select officied from budgettable
where 1 = case 
      when @budgetid = budgetid then 1
      when @budgetid = 7 and budgetid in (7,8,10) then 1 
      when @budgetid = 8 and budgetid in (6,8) then 1 
      end

This expands the results returned by @budgetid 7 to include 8 and 10.

like image 20
Andomar Avatar answered Dec 20 '25 13:12

Andomar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!