Discussion stickers: The visibility of temporary tables generated in sp_executesql

Source: Internet
Author: User
Tags visibility

Create a data table first

IF object_id('testtable') is  not NULL    DROP TABLEtesttableGOCREATE TABLETestTable (IDINT IDENTITY(1,1), InfoVARCHAR(Ten))GOINSERTTestTableSELECT 'a'UNION  All SELECT 'b'GO

Then execute the following three scripts in turn

Script one:

EXEC (' SELECT * to #temp from TestTable ')
SELECT * from #temp

Script two:

exec sp_executesql N ' SELECT * to #temp from TestTable '
SELECT * from #temp

Script Three:

SELECT * to #temp from TestTable
EXEC (' SELECT * from #temp ')

--drop TABLE #temp

After execution, it is found that only the third script is successful, and other scripts will prompt after execution:

MSG 208, level A, state 0, line 2
Invalid object name ' #temp '.

Their different expenditures are the order in which SQL statements are executed,

My understanding is:

Changes made to the database context are only valid until the exec sp_executesql, or exec (' ... ') statement ends.

If the temporary table is generated before sp_executesql, then it is willing to receive, if the sp_executesql is executed first to create the temporary table,

When the statement is finished, the temporary table disappears.

Expect to hear more authoritative answers ...

Discussion stickers: The visibility of temporary tables generated in sp_executesql

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.