T-SQL Dynamic SQL and Temp Tables

前端 未结 5 1869
梦毁少年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 12:06

    1st Method - Enclose multiple statements in the same Dynamic SQL Call:

    DECLARE @DynamicQuery NVARCHAR(MAX)
    
    SET @DynamicQuery = 'Select * into #temp from (select * from tablename) alias 
    select * from #temp
    drop table #temp'
    
    EXEC sp_executesql @DynamicQuery
    

    2nd Method - Use Global Temp Table:
    (Careful, you need to take extra care of global variable.)

    IF OBJECT_ID('tempdb..##temp2') IS NULL
    BEGIN
        EXEC (
                'create table ##temp2 (id int)
                 insert ##temp2 values(1)'
                )
    
        SELECT *
        FROM ##temp2
    END
    

    Don't forget to delete ##temp2 object manually once your done with it:

    IF (OBJECT_ID('tempdb..##temp2') IS NOT NULL)
    BEGIN
         DROP Table ##temp2
    END
    

    Note: Don't use this method 2 if you don't know the full structure on database.

提交回复
热议问题