从执行结果中选择(@query)

时间:2012-10-30 09:27:37

标签: sql sql-server-2008

我正在使用此SQL查询

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Animal2) 
                    from animals
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT Animal1, ' + @cols + ' from 
             (
                select animal1, animal2, Corelation
                from animals
            ) x
            pivot 
            (
                min(Corelation)
                for animal2 in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with demo

当我执行查询时,我得到一个表作为返回。

如何从该表中进行选择?我尝试使用SELECT * FROM (*past here the script*)但它没有用。我只需要将execute(@query)的结果用作表并从中进行选择(将其放入新表中)。我该怎么办?

由于

注意:该查询是this SO question

的答案

2 个答案:

答案 0 :(得分:3)

使用Insert into ... exec格式,如下所示:

CREATE TABLE #tmp1 (
   [Animal1] varchar(5), 
   [Cat] decimal(10, 5), 
   [Dog] decimal(10, 5), 
   [Mouse] decimal(10, 5)
)

Insert Into #Tmp1
 execute(@query)  

select * from #tmp1
  where cat = 1

当然,由于列名是动态的,因此您还需要将create语句转换为动态sql。

SQL Fiddle with the fixed version

SQL Fiddle with the dynamic version

答案 1 :(得分:1)

使用into和全局临时表 - 然后您不必提前定义表列。

set @query = 'SELECT Animal1, ' + @cols + 
    +' into ##temp '
    +' from 
             (
                select animal1, animal2, Corelation
                from animals
            ) x
            pivot 
            (
                min(Corelation)
                for animal2 in (' + @cols + ')
            ) p '

select * from ##temp