动态枢轴结果到临时表

时间:2014-03-19 10:48:53

标签: sql sql-server tsql

虽然我能够找到如何在这些论坛中转移这些数据,但我还是找不到将结果推送到临时表的方法,以便我可以将其用于其他查询。代码如下。有没有办法让这个输出填充临时表?

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(QT.QUESTION_DESC)
                 FROM #QUES_TEMP QT
                 GROUP BY QT.QUESTION_DESC
                 FOR XML PATH(''), TYPE
                 ).value('.', 'NVARCHAR(MAX)')
                 ,1,1,'')

set @query = 'SELECT EVAL_ID, AuditType, ' + @cols + ' 
            into ##tmp
            from
        (
            select     QT.EVAL_ID,
                       QT.AuditType,
                       QT.SCORE,
                       QT.QUESTION_DESC

            from #QUES_TEMP QT
         ) x

        pivot
        (
             max(SCORE)
             for QUESTION_DESC in (' + @cols + ')
        ) p '

execute(@query);

select * from ##tmp

2 个答案:

答案 0 :(得分:5)

您应该可以使用INTO Clause。我在你的例子中添加了INTO。

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(QT.QUESTION_DESC)
                 FROM #QUES_TEMP QT
                 GROUP BY QT.QUESTION_DESC
                 FOR XML PATH(''), TYPE
                 ).value('.', 'NVARCHAR(MAX)')
                 ,1,1,'')

set @query = 'SELECT EVAL_ID, AuditType, ' + @cols + ' from
        (
            select     QT.EVAL_ID,
                       QT.AuditType,
                       QT.SCORE,
                       QT.QUESTION_DESC
            into ##tmp
            from #QUES_TEMP QT
         ) x

        pivot
        (
             max(SCORE)
             for QUESTION_DESC in (' + @cols + ')
        ) p '

execute(@query);

SELECT * FROM ##tmp

答案 1 :(得分:0)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(QT.QUESTION_DESC)
                 FROM #QUES_TEMP QT
                 GROUP BY QT.QUESTION_DESC
                 FOR XML PATH(''), TYPE
                 ).value('.', 'NVARCHAR(MAX)')
                 ,1,1,'')

set @query = 'SELECT EVAL_ID, AuditType, ' + @cols + ' 
            from
        (
            select     QT.EVAL_ID,
                       QT.AuditType,
                       QT.SCORE,
                       QT.QUESTION_DESC

            from #QUES_TEMP QT
         ) x

        pivot
        (
             max(SCORE)
             for QUESTION_DESC in (' + @cols + ')
        ) p '

set @query = 'select * into ##Temp from ('+@query+') y'
execute(@query)
select * from ##Temp