首页 > 解决方案 > 使用 IF 条件在 SQL Server 中的 UNION 内获取查询

问题描述

有什么办法可以做到以下(示例)。不使用临时表exec

SELECT 'apple' fruit, 'Dog' animal, 'crow' bird
UNION
 IF ('B' = 'A') BEGIN   SELECT 'orange' fruit, 'cat' animal, 'cock' bird
 END ELSE   SELECT 'grape' fruit, 'lion' animal, 'parrot' bird  END
UNION
SELECT 'banana' fruit, 'tiger' animal, 'hen' bird

标签: sql-server

解决方案


我们可以尝试使用CASE表达式来表达联合中的中间查询:

SELECT 'apple' fruit, 'Dog' animal, 'crow' bird
UNION ALL
SELECT
    CASE WHEN <some_condition> THEN 'orange' ELSE 'grape' END,
    CASE WHEN <some_condition> THEN 'cat'    ELSE 'lion' END,
    CASE WHEN <some_condition> THEN 'cock'   ELSE 'parrot' END
UNION ALL
SELECT 'banana', 'tiger', 'hen';

提示:只会使用联合中第一个查询的别名。其他的将被忽略,因此在其他地方添加别名没有意义。


推荐阅读