Insert dynamic pivot data into a #tmp table rather than a ##tmp table

moondaddy 916 Reputation points
2020-09-10T04:11:22.903+00:00

I need to insert data from a dynamic pivot table into a temp table, however, the only way I can get it to work is using a ## global temp table rather than a # local table. The stored procedure using this is for generating report data and if we use the ## version there's a chance we'll get conflicts with two instances of this running at the same time.

Any recommendations?

Thank you.

Developer technologies | Transact-SQL
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. moondaddy 916 Reputation points
    2020-09-10T16:42:24.733+00:00

    Thanks but because it's a dynamic pivot I will not know the table structure. The pivot columns are a complete unknown.

    1 person found this answer helpful.

  2. MelissaMa-MSFT 24,221 Reputation points
    2020-09-10T05:54:36.727+00:00

    Hi @moondaddy ,

    You could declare the temporary table structure outside dynamic sql, then avoid to use global temporary table.

    Please refer below example and check whether it is helpful to you.

    create table testtable  
    (ID int,Name varchar(10))  
      
    insert into testtable values (1,'A')  
      
    if object_id('tempdb..#Test')  is not null drop table #Test  
      
    create table #Test (ID int,Name varchar(10))   
      
    declare @query nvarchar(max)  
      
    set @query = N'   
    insert into #Test select * from testtable  
     '  
    exec sp_executesql @query;  
      
    select * from #Test  
    

    But it could be better for you to provide table CREATE TABLE statements for your tables together with INSERT statements with sample data, your dynamic pivot statement, enough to illustrate all angles of the problem.

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.