简体   繁体   English

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

[英]Insert dynamic query results into un-defined temp table?

I'm defining a long dynamic query and I'd like to insert it's results into a table.我正在定义一个长动态查询,我想将它的结果插入到一个表中。 However, I'd prefer not to define the table first.但是,我不想先定义表格。 Is this possible?这可能吗?

The query works correctly, I see the expected results if I run this:查询工作正常,如果我运行这个,我会看到预期的结果:

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

But neither of these attempts to select into an un-defined temp table work:但是这些尝试选择未定义的临时表都不起作用:

--attempt 1
    declare @query VARCHAR(MAX)
    @query = 'SELECT * INTO #T1 (
                SELECT
                   --a bunch of stuff involving joins and pivots and such
                )
             '
    execute (@query)

--attempt 2
    declare @query VARCHAR(MAX)
    @query = 'SELECT
                   --a bunch of stuff involving joins and pivots and such
             '
    execute (@query)
    select * INTO #T1  execute (@query)

One workaround is to use global temp table:一种解决方法是使用全局临时表:

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

The normal local temporary table won't work, because Dynamic SQL creates new context.普通的本地临时表将不起作用,因为动态 SQL 会创建新的上下文。 The table is in that context and will cease to exist when code is executed, so you cannot use it outside Dynamic-SQL.该表位于该上下文中,并且在执行代码时将不复存在,因此您不能在 Dynamic-SQL 之外使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM