Push results of dynamic SQL statement into temp table

I have created a dynamic SQL statement which creates a pivot table for records in a combination of tables.

When I run this:


it returns a recordset, but this is only an intermediate step, as this data then needs to be merged into another table.

So, how do I get the results of Execute(@query) into a temporary table which I can then use in an update query where these results are joined to the destination table on Bolo_ID and RecordDate?
LVL 51
Dale FyeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dorababu MSenior Software EngineerCommented:
You can do as follows

DECLARE @query_from NVARCHAR(MAX) = ''

CREATE TABLE #TableVariable (ID INT)
INSERT INTO #TableVariable VALUES (1),(2)

SET @query_from = @query_from + CHAR(10) + ' JOIN #TableVariable on Customer.Id = #TableVariable.ID ' 
SET @query = 'SELECT * FROM Customer ' + @query_from

EXECUTE sp_executesql @query

Open in new window

Dale FyeAuthor Commented:

I really hate editing dynamic SQL (embedded quotes are a nightmare!), which is why I was hoping that after creating the query that generates that table (@Query), I could simply generate those results into a temp table (physical or memory) and use that temp table as the source in my subsequent MERGE statement.

ste5anSenior DeveloperCommented:
I have created a dynamic SQL statement which creates a pivot table for records in a combination of tables. [..]
 it returns a recordset, but this is only an intermediate step, as this data then needs to be merged into another table.
Pivoting should be the last step in your processing. Then you would not need that string fiddling in the dynamic SQL string.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
The only way I've ever known to pull this off is to construct your pivot table so that the columns have defined names, such as CurrentMonth, CurrentMonthMinusOne, CurrentMonthMinusTwo, etc. such that a direct mapping can take place between your pivot table and the downstream table.

Otherwise, how would the downstream table know what columns to use?

Good luck.
Scott PletcherSenior DBACommented:
INSERT INTO #table_name --( col_name1, col_name2, ... )

Of course the temp table must already exist.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Dale FyeAuthor Commented:
I'll have to test that Scott, never considered that it might be that easy.
ste5anSenior DeveloperCommented:
And the column order must match..

the easy approach is to postpone the pivoting to the end of the processing.
Scott PletcherSenior DBACommented:
And the column order must match..

I don't think it does, as long as you specify the column(s) in the receiving table.
Dale FyeAuthor Commented:
Thanks guys.

Scott's solution was precisely what I was looking for.

The pivot has two base columns and will always contain the same three pivot columns.  This is done to get the data into a format which is easily to join with the destination table on the two base columns, allowing me to easily set the values of the three columns based on the merge.

The column order is immaterial as the merge statement specifies which columns in the target to update from which column in the source.

I know I could have probably done this more elegantly with three separate merge or update queries but I just wanted to try this.

Mark EdwardsChief Technology OfficerCommented:

Here's a little code I use to put the results of any select query into a temp table without knowing the field names:

IF(OBJECT_ID('tempdb..#Table1','U') IS NOT NULL)
     DROP TABLE #Table1
SELECT * INTO [#Table1] FROM (
pivot query sql
) AS qryPivot
 WHERE .....

I know you can figure out the rest....
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.