views:

1031

answers:

2

I've seen this, so I know how to create a pivot table with a dynamically generated set of fields. My problem now is that I'd like to get the results into a temporary table.

I know that in order to get the result set into a temp table from an EXEC statement you need to predefine the temp table. In the case of a dynamically generated pivot table, there is no way to know the fields beforehand.

The only way I can think of to get this type of functionality is to create a permanent table using dynamic SQL. Is there a better way?

+1  A: 

you could do this:

-- add 'loopback' linkedserver 
if exists (select * from master..sysservers where srvname = 'loopback')
    exec sp_dropserver 'loopback'
go
exec sp_addlinkedserver @server = N'loopback',
    @srvproduct = N'',
    @provider = N'SQLOLEDB', 
    @datasrc = @@servername
go

declare @myDynamicSQL varchar(max)
select @myDynamicSQL = 'exec sp_who'
exec('
    select * into #t from openquery(loopback, ''' + @myDynamicSQL + ''');
    select * from #t
    ')

EDIT: addded dynamic sql to accept params to openquery

Mladen Prajdic
How do you pass dynamic SQL to OPENQUERY?
brian
you don't. you'll have to make that dynamic too.
Mladen Prajdic
Not sure I understand, please clarify
brian
i've edited the post to reflect the changes
Mladen Prajdic
In this scenario, #t is out of scope outside the EXEC statement
brian
well then you can put it into a global ##temp table
Mladen Prajdic
+1  A: 

Let me try this explanation of select into instead. I'm running SQL Server 2005 as well. Because you have PIVOT tables I'm going to assume the same or 2008.

select 
    o.*,
    OtherField1,
    OtherField2
INTO #temp
FROM
    OriginalOtherData as ood
PIVOT (
    MAX([Value])
    FOR Field in (OtherField1, OtherField2)
) as piv
RIGHT OUTER join
    Original o on o.OriginalSD = piv.OriginalSD

select * from #temp
Drop table #temp

The only difference between a normal select and a select into is that INTO #table part.

Min
Please read the linked-to question. I am using dynamic SQL to generate the field list for the pivoted table. You cannot use SELECT INTO with an EXEC unless you have a table already created. Since I don't know the field list of the result of the EXEC, I cannot precreate the table.
brian
You're already dynamically generating the field list. So why not use that code to help generate the table definition?Also, is there something that prevents MSSQL from doing your SELECT INTO within the EXEC, and not outside of it?
Min
The answer to both of those questions is that the scope of a temp table created inside a dynamic SQL query would make it inaccessible to the procedure/query that made the EXEC call.
brian
Well there are global temporary tables. Just use ## instead of # in the name, but then again you have a global temporary table to deal with.
Min