T-SQL Dynamic SQL and Temp Tables

前端 未结 5 1874
梦毁少年i
梦毁少年i 2020-11-28 11:04

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

5条回答
  •  不知归路
    2020-11-28 11:49

    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.

提交回复
热议问题