sql-server - 使用 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
解决方案
我们可以尝试使用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';
提示:只会使用联合中第一个查询的别名。其他的将被忽略,因此在其他地方添加别名没有意义。
推荐阅读
- node.js - 在嵌套数组mongodb nodejs中查找对象
- php - 添加 PHP cookie 时如何自动反映更改?
- javascript - 使用jquery在页面重定向后检索输入数据
- node.js - 错误:找不到模块“C:\Users\Elie\Projects\MEAN\task-manager\api\index.js”
- r - 需要 64 种颜色的调色板:简单的热图问题
- java - 在Java中返回旋转的矩形
- php - 条件 PHP 代码不接受值
- node.js - 如何添加在 ejs 节点应用程序中呈现的捆绑文件(使用 ejs 创建)?
- python - 有没有办法在 Python 中使用 AutoKey 的缩写粘贴本地图像?
- javascript - 在 JavaScript 中将日期格式更改为特定格式