T-SQL Dynamic SQL and Temp Tables

前端 未结 5 1872
梦毁少年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:47

    You first need to create your table first then it will be available in the dynamic SQL.

    This works:

    CREATE TABLE #temp3 (id INT)
    EXEC ('insert #temp3 values(1)')
    
    SELECT *
    FROM #temp3
    

    This will not work:

    EXEC (
            'create table #temp2 (id int)
             insert #temp2 values(1)'
            )
    
    SELECT *
    FROM #temp2
    

    In other words:

    1. Create temp table
    2. Execute proc
    3. Select from temp table

    Here is complete example:

    CREATE PROC prTest2 @var VARCHAR(100)
    AS
    EXEC (@var)
    GO
    
    CREATE TABLE #temp (id INT)
    
    EXEC prTest2 'insert #temp values(1)'
    
    SELECT *
    FROM #temp
    

提交回复
热议问题