如果现在没有数据,如何确保始终返回结果集?
现在,如果#TMP_SUMMARY1
没有返回任何行。
如何确保以下查询返回给我一个没有行的表,而不只是显示此消息选项卡,下面显示此消息并且没有结果选项卡。
(0行(s)受影响)
这种情况下没有返回结果集会让我成为一场噩梦!
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
答案 0 :(得分:1)
如果#TMP_SUMMARY1中没有行,则@ cols1和@colsum1的值将为null,并且动态sql将具有无效语法。为什么不用
包装动态sqlIf (@cols1 is not null)
并且在没有列时不执行该语句。