扩展TSQL语句以循环动态查询的结果

时间:2015-05-28 03:44:50

标签: sql sql-server

以下SQL输出动态no列。数据具有准确的初始格式,用于准备要传递到谷歌图表的字符串。问题是,我得到了很好的输出到管理工作室的结果(作为一个表)。但现在我想循环这些结果并构建一个字符串以作为图表源返回..

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT @cols = STUFF((SELECT distinct 
                        ',' +
                        QUOTENAME(MeterReadType)
                 FROM MeterReadView with (nolock)
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'');

SET @query = ' SELECT MeterReadMonth as Month,  ' + @cols + ' 

FROM 
(
   SELECT MeterReadType, MeterReadMonth,isnull(total,0) as total
   FROM [MeterReadView] with (nolock)
) t
PIVOT
( 
  sum(total)
  FOR MeterReadType IN (' + @cols + ' )
) 
p ' ;

Execute(@query);

以上SQL输出如...

Month   Desc 1, Desc 2, Desc 3, etc and so on.. 
2014-06 4       5       66
2014-06 9       3       7

但我需要循环结果并以下列格式构建一个字符串。我不能只加载到MVC,因为我需要指定一个类,我不知道会有多少列,所以我只是在SQL中构建一个字符串。后者我能做到。只是不确定如何扩展这个现有的SQL进入一个循环,因为它的执行(@query),如何将它变成一个知道没有列的临时表?

     [['Month','Desc 1','Desc 2','Desc 3'],
     ['Jun-14',4,5,66],
     ['Jun-14',9,3,7], 
['May-15',20,66,5]]

2 个答案:

答案 0 :(得分:0)

John我为你准备了一个样本,我没有时间给出确切的信息,但你理解逻辑。

逻辑是,您可以在运行时将此输出存储在临时表中(运行时意味着在动态查询中),然后按如下方式编写代码。

EXECUTE ('SELECT * INTO #TEMP  FROM ' + @TableName +'; SELECT * FROM #TEMP;')

此链接可帮助您在动态查询中创建临时表。

TSQL select into Temp table from dynamic sql

Using a temporary table in dynamic sql in a stored procedure

Dynamic SQL results into temp table in SQL Stored procedure

--create table #t(month varchar(50) , [desc 1] int , [desc 2] int, [desc 3] int)

--insert into #t values ( '2014-06', 4,5,66 ) , ( '2014-06', 4,5,66 )

--select datename(month, getdate())
select datename(month, cast( month + '-01' as date)), 
* from #t

declare @month varchar(50), @desc1 varchar(50) , @desc2 varchar(50) , @desc3 varchar(50) , @str nvarchar(max) = '['
DECLARE Cur CURSOR FOR

        select *  from #t
        Open Cur

    Fetch Next from Cur INTO @month, @desc1, @desc2, @desc3
    While(@@fetch_status=0)                                                                                                                                                                                                     While(@@fetch_status=0)
    BEGIN
         select convert(char(3),cast( @month + '-01' as date) ,0),  @month, @desc1, @desc2, @desc3
          if(len(@str) > 1) set @str = @str + ', '
         set @str = @str + '[''' + convert(char(3),cast( @month + '-01' as date) ,0) + ''',''' + @desc1 + ''',''' + @desc1 + ''',''' + @desc1 + ''']'
    Fetch Next from Cur INTO @month, @desc1, @desc2, @desc3
    END
Close Cur
Deallocate Cur

set @str = @str + ']'
select @str

答案 1 :(得分:0)

您可以使用此查询可能是此查询中存在一些语法错误,因为您未提供示例数据请更正它们,这是没有临时表的。

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @colssplit AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT @cols = STUFF((SELECT distinct 
                        ',' +
                        QUOTENAME(MeterReadType)
                 FROM MeterReadView with (nolock)
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'');

SELECT @colssplit = STUFF((SELECT distinct 
                        ' + '',''+ CAST( ' +
                        QUOTENAME(MeterReadType) + ' AS Varchar(10))'
                 FROM MeterReadView with (nolock)
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'');


SET @query = ' SELECT ''[[''+''MOnth'','+@cols+']' +  ( SELECT (SELECT '+  '['''+  '[Month]' + ''',' + @colssplit + ' FROM ( select * from (   SELECT MeterReadMonth as Month,  ' + @cols + ' 

FROM 
(
   SELECT MeterReadType, MeterReadMonth,isnull(total,0) as total
   FROM [MeterReadView] with (nolock)
) t
PIVOT
( 
  sum(total)
  FOR MeterReadType IN (' + @cols + ' )
) 
p ) Mydata  for XML PATH ('') ,Type ).value('.', ''NVARCHAR(MAX)'') AS  ' ;