0

即使当前没有数据,如何确保这始终返回结果集?

现在如果#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  
4

1 回答 1

1

如果#TMP_SUMMARY1 中没有行,则@cols1 和@colsum1 的值将为空,并且您的动态sql 将具有无效的语法。为什么不直接用一个包裹你的动态 sql

If (@cols1 is not null)

并且在没有列时不执行该语句。

于 2013-03-14T13:28:18.230 回答