It looks like #temptables created using dynamic SQL via the EXECUTE string method have a different scope and can\'t be referenced by \"fixed\" SQLs in the same stored proced
I had the same issue that @Muflix mentioned. When you don't know the columns being returned, or they are being generated dynamically, what I've done is create a global table with a unique id, then delete it when I'm done with it, this looks something like what's shown below:
DECLARE @DynamicSQL NVARCHAR(MAX)
DECLARE @DynamicTable VARCHAR(255) = 'DynamicTempTable_' + CONVERT(VARCHAR(36), NEWID())
DECLARE @DynamicColumns NVARCHAR(MAX)
--Get "@DynamicColumns", example: SET @DynamicColumns = '[Column1], [Column2]'
SET @DynamicSQL = 'SELECT ' + @DynamicColumns + ' INTO [##' + @DynamicTable + ']' +
' FROM [dbo].[TableXYZ]'
EXEC sp_executesql @DynamicSQL
SET @DynamicSQL = 'IF OBJECT_ID(''tempdb..##' + @DynamicTable + ''' , ''U'') IS NOT NULL ' +
' BEGIN DROP TABLE [##' + @DynamicTable + '] END'
EXEC sp_executesql @DynamicSQL
Certainly not the best solution, but this seems to work for me.