Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

SQL Server 2005 and temporary table scope

I've read around the subject of temporary tables and scope and all the answers i've seen don't seem to talk about one of my concerns.

I understand that a local temporary table's scope is only valid withing the lifetime of a stored procedure or child stored procedures. However what is the situation with regard to concurency. i.e. if i have a stored procedure that creates a temporary table which is called from two different processes but from the same user/connection string, will that temporary table be shared between the two calls to that one stored procedure or will it be a case of each call to the stored procedure creates an unique temporary table instance.

I would assume that the temporary table belongs to the scope of the call to the stored procdure but i want to be sure before i go down a path with this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Local temporary tables (start with #) are limited to your session; other sessions, even from the same user/connection string, can't see them. The rules for the lifetime depend on whether the local temporary table was created in a stored procedure:

  • A local temporary table that is created in a stored procedure is dropped when the procedure ends; other stored procedures, or the calling process, can't see them.
  • Other local temporary tables are dropped when the session ends.

Global temporary tables (start with ##) are shared between sessions. They are dropped when:

  • The session that created them ends
  • AND no other session is referring to them

This command can be handy to see which temporary tables exist:

select TABLE_NAME from tempdb.information_schema.tables 

And this is handy to drop temporary tables if you're not sure they exist:

if object_id('tempdb..#SoTest') is not null drop table #SoTest

See this MSDN article for more information.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...