2

我想在 SQL 中的 case..when 语句中单个条件为真时显示多个语句。

例如:

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

end

谁能给我提供它的确切语法吗?提前致谢。

4

1 回答 1

2

如果您的条件很复杂,您可以将其移至子查询。这样您就不必为每一列重复它:

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

另一种选择是与 CTE 的联合(并非在所有数据库中都可用。)这允许您编写不带 的表达式case,并且由于 CTE,条件不会重复。

;       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
于 2013-01-11T09:44:16.027 回答