Could I execute multiple expressions when a single condition is true in case..when statement in SQL?

StackOverflow https://stackoverflow.com/questions/14274187

  •  14-01-2022
  •  | 
  •  

Question

I wanna display multiple statements when a single condition is true in case..when statement in SQL.

Eg:

case when (condition is true) then 
print "A" 
print "B"
.
.
.
.
print "Z"
when (condition2 is true) then 
print "Z" 
print "Y"
.
.
.
.
print "A

end

Could anyone provide me the exact syntax for it please? Thanks in advance.

Was it helpful?

Solution

If your condition is complex, you can move it to a subquery. That way you don't have to repeat it for each column:

select  case when Condition = 1 then 'A' else 'B' end
,       case when Condition = 1 then 'C' else 'D' end
,       case when Condition = 1 then 'E' else 'F' end
,       ...
from    (
        select  *
        ,       case
                when ... complex condition ... then 1 
                else 0 
                end as Condition
        from    YourTable
        ) as SubQueryAlias

Another option is a union with a CTE (not available in all databases.) That allows you to write the expressions for both without case, and thanks to the CTE the condition is not repeated.

;       with CteAlias as
        (
        select  *
        ,       case
                when ... complex condition ... then 1 
                else 0 
                end as Condition
        from    YourTable
        )
select  'A', 'C', 'E'
from    CteAlias
where   Condition = 1
union all
select  'B', 'D', 'F'
from    CteAlias
where   Condition = 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top