将动态查询结果插入未定义的临时表?

时间:2015-10-27 16:39:12

标签: sql sql-server sql-server-2008

我定义了一个长动态查询,并希望将其结果插入到表格中。但是,我不想先定义表格。这可能吗?

查询工作正常,如果我运行此命令,我会看到预期的结果:

  yum update stunnel
 Loaded plugins: fastestmirror, security
Setting up Update Process
 Loading mirror speeds from cached hostfile
  * base: repos.lax.quadranet.com
 * extras: dallas.tx.mirror.xygenhosting.com
* updates: dallas.tx.mirror.xygenhosting.com
No Packages marked for Update

但这些尝试选择进入未定义的临时表的工作都不起作用:

declare @query VARCHAR(MAX)
@query = 'SELECT
               --a bunch of stuff involving joins and pivots and such
         '
execute (@query)

1 个答案:

答案 0 :(得分:2)

一种解决方法是使用全局临时表:

SET @query = 'SELECT * INTO ##T1 FROM (
                SELECT
                   --a bunch of stuff involving joins and pivots and such
                )';

EXECUTE(@query);

SELECT *    -- reasign to local temp table to avoid reserving global ##T1 name
INTO #T1    -- if needed you can skip this part and work only on global table
FROM ##T1;

DROP TABLE ##T1;

SELECT *
FROM #T1;

LiveDemo

普通的本地临时表将不起作用,因为动态SQL会创建新的上下文。该表位于该上下文中,并且在执行代码时将不再存在,因此您无法在Dynamic-SQL外部使用它。