Question

Consider the following code:

SET @SQL1 = 'SELECT * INTO #temp WHERE ...'
exec(@SQL1)
SELECT * from #temp  (this line throws an error that #temp doesn't exist)

Apparently this is because the exec command spins off a separate session and #temp is local to that session. I can use a global temporary table ##temp, but then I have to come up with a naming scheme to avoid collisions. What do you all recommend?

Was it helpful?

Solution 4

Didn't find a workable solution that did everything I needed so I switched to using ##global temp tables instead.

OTHER TIPS

Did you try to create your template table explicitly?

Create Table #temp (..)

Try ##temp Because your dynamic query is executed on an other fibre so you cannot see its local temporay table. instead if you declare your temporary table like global it make a sens.

You can create temp before exec and use exec to populate the temp table.

An example, look at "into"

SELECT o.OrderID, o.OrderDate, od.UnitPrice, od.Quantity,
       c.CustomerID, c.CompanyName, c.Address, c.City, c.Region,
       c.PostalCode, c.Country, c.Phone, p.ProductID,
       p.ProductName, p.UnitsInStock, p.UnitsOnOrder
INTO   #temp
FROM   Orders o
JOIN   [Order Details] od ON o.OrderID = od.OrderID
JOIN   Customers c ON o.CustomerID = c.CustomerID
JOIN   Products p ON p.ProductID = od.ProductID

Can you not put your select after the insert into with a ; delimeter and run the two statements together?

Another method is to use all code inside the dynamic SQL

SET @SQL1 = 'SELECT * INTO #temp WHERE ...
SELECT * from #temp  ' 
exec(@SQL1) 

There is a method of creating dummy temp table with single identity column, then altering that table with desired schema through dynamic SQL and populating it. That way you can use temporary table both in dynamic and regular SQL, join with it...

-- Create dummy table
CREATE TABLE #tmpContactData (PK int NOT NULL IDENTITY(1,1))

-- Alter its schema
DECLARE @sqlCommand nvarchar(max)
SELECT @sqlCommand = '
ALTER TABLE #tmpContactData
ADD 
    EmployeeId int,
    Address varchar(100),
    Phone varchar(50)
'
EXECUTE(@sqlCommand)

-- Fill it
SELECT @sqlCommand = '
INSERT INTO #tmpContactData
SELECT t.EmployeeId, t.Address, t.Phone 
FROM (  SELECT EmployeeId=1000, Address=''Address 1000'', Phone=''Phone 1000'' 
        UNION 
        SELECT 1001, ''Address 1001'', ''Phone 1001'' 
        UNION 
        SELECT 1002, ''Address 1002'', ''Phone 1002''
) t
'
EXECUTE(@sqlCommand)

--select from it
SELECT * FROM #tmpContactData

--CleanUp
DROP TABLE #tmpContactData
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top