即使当前没有数据,如何确保这始终返回结果集?
现在如果#TMP_SUMMARY1
不返回任何行。
如何确保下面的查询返回给我一个没有行的表,而不仅仅是向我显示此消息选项卡,下面有此消息且没有结果选项卡。
(0 行受影响)
在这种情况下不返回结果集让我做噩梦!
IF (@SUMMARY = 'Agent Summary')
BEGIN
DECLARE @cols1 AS NVARCHAR(MAX),
@colSum1 AS NVARCHAR(MAX),
@query1 AS NVARCHAR(MAX)
select @cols1 = STUFF((SELECT distinct ',' + QUOTENAME(Agent)
from #TMP_SUMMARY1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)') ,1,1,'')
print @cols1
select @colSum1 = STUFF((SELECT distinct ', Sum(' + QUOTENAME(Agent)+') as ' +QUOTENAME(Agent)
from #TMP_SUMMARY1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)') ,1,1,'')
print @colSum1
set @query1 = 'select
case when [PAYMENT TYPE] is null then ''*GRAND TOTAL'' else [Credit/Debit] end [Credit/Debit],
case when [PAYMENT TYPE] is null then '''' else [PAYMENT TYPE] end [PAYMENT TYPE],
'+@colSum1 +'
from
(
select [Agent] ,
[Credit/Debit],
[PAYMENT TYPE],
value
from #TMP_SUMMARY2
unpivot
(
value
for [Credit/Debit] in ([Amount Credit], [Amount Debit])
) unpiv
) src
pivot
(
sum(value)
for agent in ('+@cols1+')
) piv
group by GROUPING SETS ([Credit/Debit], [PAYMENT TYPE]), ([Credit/Debit])'
execute(@query1)
END