简体   繁体   中英

Dynamic Query not writing into temp table

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


select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(hi)
                      FROM #hello 
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');
--select @cols                         

The above code for some reason is not entering date into the #storage temp table? Why is that happening?

select @query = 'SELECT *
into #storage 
FROM (
SELECT *
FROM #hello) up
PIVOT ( MAX(AFEAmount) FOR hi IN (' + @cols + ') ) AS pvt'

exec(@query)

The code is crete the temp table #storage . The problem is that the table is not "in scope", so you cannot access it outside the exec() statement. Temporary tables are limited in scope to the particular process that creates them. The temporary table is available when exec() is running but not outside it. There is some explanation of this in the documentation ( here ).

In some cases, you can get around this by using the insert . . . exec() insert . . . exec() insert . . . exec() form of the statement. If the table were permanent, you would construct the create table statement for it, and then do:

 insert into storage(...)
     exec(@query);

Or, you could even do this inside the dynamic SQL, because the permanent table persists across sessions.

The problem with the temporary table, in this case, is that you don't know its structure. You need to create the table before doing the insert. A variable structure requires dynamic SQL, and you have the same problem when creating the table. It is created at the "wrong" lvel.

You could change the table to a global temporary table (those that begin with ##). This has scoping across different processes.

Or, you could create a persistent table with a funky name (I would use _storage or _storage_YYYYMMDDHHMMSS where the latter has a time stamp at the end). Just remember to delete the table when you are done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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