存储过程到具有可变列数的表

时间:2012-04-07 00:10:16

标签: sql-server-2005 stored-procedures

当结果可以有多少列时,如何将SP的输出插入表中?

此SP创建一个表格,列数可能会有所不同。我需要将结果放入临时表中,以便我可以使用它来查询报告。如何创建可以处理SP输出的表?

 DECLARE @cols AS VARCHAR(MAX),
 @query  AS VARCHAR(MAX); 

 SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.question) 
        FROM temp_SURVEY_DATA c
        FOR XML PATH(''), TYPE
        ).value('.', 'VARCHAR(MAX)') ,1,1,'')

 set @query =  'SELECT responseid, moduleid, responsedatetime, ' + @cols + ' from 
        (select question, response, responsedatetime, responseid, moduleid
            from temp_SURVEY_DATA) x
        pivot 
        ( max(response)
            for question IN(' + @cols + ') ) p '

          execute(@query)

1 个答案:

答案 0 :(得分:0)

使用专门用于此类事物的静态表并将结果集插入其中,而不是将行返回给调用者:

DECLARE @cols AS VARCHAR(MAX),
        @query  AS VARCHAR(MAX); 

 SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.question) 
        FROM temp_SURVEY_DATA c
        FOR XML PATH(''), TYPE
        ).value('.', 'VARCHAR(MAX)') ,1,1,'');

EXECUTE ('IF OBJECT_ID(''temp_SURVEY_DATA_pivoted'') IS NOT NULL
  DROP TABLE temp_SURVEY_DATA_pivoted');

set @query =  'SELECT responseid, moduleid, responsedatetime, ' + @cols + '
  INTO temp_SURVEY_DATA_pivoted
  from 
        (select question, response, responsedatetime, responseid, moduleid
            from temp_SURVEY_DATA) x
        pivot 
        ( max(response)
            for question IN(' + @cols + ') ) p '

          execute(@query)

或者在显示数据之前的其他地方使用动态脚本时放弃动态脚本的想法。