Consider the following code:
SET @SQL1 = \'SELECT * INTO #temp WHERE ...\'
exec(@SQL1)
SELECT * from #temp (this line throws an error that #temp doesn\'t ex
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
Did you try to create your template table explicitly?
Create Table #temp (..)