仅当查询返回行时,才需要向存储过程的结果数据集中添加标题。
尝试使用联合将列标题添加到结果数据集中,但我只希望在从查询返回其他行时列标题存在。
如果没有其他记录,我需要的结果是一个零字节的文件(没有标题)。
将@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
发布于 2019-01-23 05:32:37
对您的查询使用公用表表达式,因此您不必重复它:
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
发布于 2019-01-23 04:39:52
将same FROM子句和TOP 1添加到您的“虚拟列名称”部分。如果没有记录,它将不返回任何内容,如果有记录,它将返回一行。
SELECT TOP 1
'Column One',
'Column Two',
1 AS SortOrder
FROM [dbo].[myTable]
WHERE [Col1] = @myValue
AND @@RowCount > 0
UNION ALL
SELECT cast([Col1] AS varchar),
cast([Col2] AS varchar),
2 AS SortOrder
FROM [dbo].[myTable]
WHERE [Col1] = @myValue
AND @@RowCount > 0
ORDER BY SortOrder
https://stackoverflow.com/questions/54320010
复制相似问题