首页 > 解决方案 > 如何将列标题包含到结果数据集中,但前提是查询返回行?

问题描述

需要向存储过程的结果数据集添加标题,但前提是查询返回行。

尝试使用联合将列标题添加到结果数据集,但我只希望在查询返回其他行时存在列标题。

如果没有其他记录,我需要将结果设为零字节文件(无标题)。

将@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

标签: sqltsql

解决方案


为您的查询使用公用表表达式,因此您不必重复它:

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

推荐阅读