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.
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