0

This is running on SQL Server 2008, but the database is in SQL Server 2000 compatibility mode (this I cannot change).

A temporary table is created at the beginning of the stored procedure and then insert into via an EXEC statement from dynamically generated SQL. How is this executing successfully, even though the temporary table (should be, from my understand) is out the execution scope, or does this get bypassed temporarily when performing these statements inside a stored procedure?

Example below:

CREATE PROCEDURE myProc (Param1 int....)
AS
BEGIN
   Declare @SQL varchar(max) = null

   Create table #tempTable 
   (
       ID int,
       Code1 varchar(255),
       ...
   )

   SET @SQL = 'insert into #tempTable '
              + ...
   EXEC(@SQL)

   Select * from #tempTable
END

Any help understanding this would be greatly appreciated!

Thanks!

1
  • Temporary tables have dynamic scope, not lexical scope. Commented Sep 17, 2015 at 21:42

1 Answer 1

3

Shortly: The temporary table created in the outer batch is accessible inside the dynamic SQL but not vice versa.

See doc

A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process that called the stored procedure that created the table.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.