sql - 如何将列标题包含到结果数据集中,但前提是查询返回行?
问题描述
需要向存储过程的结果数据集添加标题,但前提是查询返回行。
尝试使用联合将列标题添加到结果数据集,但我只希望在查询返回其他行时存在列标题。
如果没有其他记录,我需要将结果设为零字节文件(无标题)。
将@myValue 声明为 int = 999
select
'Column One'
,'Column Two'
union all
select cast([Col1] as varchar)
,cast([Col2] as varchar)
FROM [dbo].[myTable]
where [Col1] = @myValue
and @@RowCount > 0
解决方案
为您的查询使用公用表表达式,因此您不必重复它:
with cte(c1, c2) as
(
select cast([Col1] as varchar)
,cast([Col2] as varchar)
from [dbo].[myTable]
where [Col1] = @myValue
)
select c1, c2
from
(
select c1, c2, 2 as c3
from cte
union all
select 'Column One'
,'Column Two'
, 1
where exists
(
select 1
from cte
)
) order by c3
推荐阅读
- android - 单击按钮时不会转到另一个视图
- angular - 离子“离子按钮”不是已知元素:“我该如何解决这个问题?
- google-kubernetes-engine - 用户在使用 Workload Identity 时无权充当服务帐户
- c++ - C++ 使用套接字从 URL 下载文件
- c# - 字符串上的 Any()
- web-scraping - 通过 colab 将音频和相关文本从 ganjoor 站点抓取为波斯语语音到文本数据库
- python - 安装 pyenv-win 后本地 python 版本没有改变
- wordpress - Wordpress:是否有插件来检查登录用户是否在谷歌表格中?
- java - 在运行时选择 2 个 Bean
- bootstrap-4 - 如何自定义 Bootstrap 的文件以仅获取使轮播组件工作所需的内容?