Multiple sessions on Stored Procedure in SQL Server - sql

I have a stored procedure in SQL Server in which I am creating couple of temp tables within and manipulating them as per my business logic and at the end I’m deleting those temp tables by using drop table query in the procedure itself.
I have a question, if multiple users are operating at the same time the what will be the case of temp tables? Will it provide multiple instances as sessions in asp.net or only one instance will be available for all users?
Please suggest a good approach for this.

Local temporary tables:
are visible only to the current connection for the user, and they are
deleted when the user disconnects from the instance of SQL Server
If your ASP.NET application creates a separate connection for each user request, then each connection will have its own temporary tables - they won't be shared with other users.

Related

ASynchronous Creation of Temp Tables in SQL Server

I'm currently trying to determine possible issues with creating temporary tables from a web application and how SQL Server naturally determines separate sessions.
SELECT blabla, lala FROM table INTO #TempTable
SELECT blabla FROM #TempTable
DROP TABLE #TempTable
In the above, while one user of a web application is waiting for the second line to execute, and another user fires off the same 3 lines, what would determine whether the 2nd user gets a "Object already exists" or else a new #TempTable is created for that user.
If each user was on a separate computer on the same network, would SQL server treat this as separate sessions and thus create separate temporary tables.
What about if it is run on the same computer on two different networks?
Each user connection to the database is it own session. These sessions are unique even if you're using connection pooling within SQL Server. Behind the scenes, SQL Server appends each #tempTable with a single session reference number, so they technically aren't even named the same thing during execution.
If the root of your problem is an error message about the object already existing when you are debugging. Try adding the code snippet below before you create the temp table:
IF OBJECT_ID('[tempdb]..[#tempTable]') IS NOT NULL
BEGIN
DROP TABLE #tempTable
END
SQL Server does not determine separate sessions.
It is a client application who create sessions. You can write an application where all traffic to the database use single connection (not so easy) or a separate connection is created for each page (common mistake). Both of the solutions are pretty bad.
In proper design you should use connection pooling and your code should reserve connections from the connection pool as needed.
Even if you are using connection pooling, it is possible that each command is executed on a different connection from the pool.

MS SQL Temporary table

I was wondering, what is the difference between these two scripts?
SELECT * FROM ##TEMP
and this
SELECT * FROM #TEMP
##TEMP is global temporary table, #TEMP is local.
Local temporary tables are visible only to their creators during the same connection to an instance of SQL Server as when the tables were first created or referenced. Local temporary tables are deleted after the user disconnects from the instance of SQL Server.
Global temporary tables are visible to any user and any connection after they are created, and are deleted when all users that are referencing the table disconnect from the instance of SQL Server.
see documentation.
Actually here is almost the same question with answer - Local and global temporary tables in SQL Server.
The first one (##TEMP) is global - anyone can access it's content and also you can from different sessions (think of tabs in SQL Server Management Studio). The other is only visible by you.
## are global tables which are visible to everyone and are deleted when all the connections that are referencing them are closed.
# are local tables that is visible to only the connection that has created it and are deleted once that connection has been disconnected.

Can many Users open a SP with a TempTable in it?

After a user is logged into his system and opens my progamm he can see data from a database depending on his WindowsUsername(I wrote a little stored procedure for that).
This Data comes from a query with a temporary Table (#temp). My question is now, if many users use this programm, after opening it they would all try to build the #temp Table within the stored procedure. Is that even possible?? Because if i try to build a tempTable with the same name the server gives me an error. Do i have to give dynamic TempTable names maybe according to the user who is logged in??? Or is there another better option?
MS-SQL Server
A local temp table (one #TableName) is per session/connection
Many users can not share a session/connection
So, a local temp table in a stored procedure is safe for may concurrent users
On the other hand you use a global temp table (##TableName) then it is visible to world+dog
From MSDN (my bold)
There are two types of temporary tables: local and global. Local temporary tables are visible only to their creators during the same connection to an instance of SQL Server as when the tables were first created or referenced. Local temporary tables are deleted after the user disconnects from the instance of SQL Server. Global temporary tables are visible to any user and any connection after they are created, and are deleted when all users that are referencing the table disconnect from the instance of SQL Server.
If it is a true temp table within a stored procedure (SP) then the temp table is created/only exists during the execution of the SP. If the sp is run multiple times by multiple users at the same time the temp table is created multiple times and stored in its own memory space for each user.
The results returned to each user will be unique and each copy of the temp table will not see the temp table from other sp calls.
If you are testing in a query window by creating the temp table twice then you will get an error.
To prove that the above works schedule the SP to run twice at the same time passing a different user id. You will get two different result sets.

Temp Table usuage in a Multi User Environment

here's the situation:
I have an SSRS report that uses an SP as a Dataset. The SP creates a Temp Table, inserts a bunch of data into it, and select's it back out for SSRS to report. Pretty straight forward.
Question:
If multiple users run the report with different parameters selected, will the temp table created by the SP collide in the tempdb and potentially not return the data set expected?
Most likely not. If the temp table is defined as #temp or #temp, then you're safe, as those kind of temp tables can only be accessed by the creating connection, and will only last for the duration of the execution of the stored procedure. If, however, you're using ##temp tables (two "pound" signs), while those tables also only last for as long as the creating stored procedure runs, they are exposed to and accessible by all connections to that SQL instance.
Odds are good that you're not using ##tables, so you are probably safe.
A temp table with a single # is a local temporary table and its scope is limited to the session that created it, so collisions should not be a problem.

How tempDB works?

I am trying to understand the tempDB and following are the doubts popping in my mind.
What is the lifetime of data in tempDB? Say a query is doing some Order By and uses tempDB for performing that. After this query finishes, someone else also executes a query which utilizes the tempDB. Will the second query find records written by first query in the tempDB or will they be deleted?
Are there any visible tables created inside the tempDB by the Sql Engine? How can I know which temporary table is created because of this query? Is there any naming convention followed by the Sql engine for naming these temporary tables?
I am new to tempDB so please pardon me for asking such silly (if at all) questions :-)
It will be very nice if someone can point me to a good resource which can help me learn about tempDB.
Temp table is stored in tempdb until the connection is dropped (or in the case of a global temp tables when the last connection using it is dropped). You can also (and it is a good practice to do so) manually drop the table when you are finished using it with a drop table statement.
No, others cannot see your temp tables if they are local temp tables (They can see and use global temp tables) Multiple people can run commands which use the same temp table name but they will not be overlapping in a local temp table and so you can have a table named #test and so can 10,000 other users, but each one has its own structure and data.
You don't want to generally look up temp tables in tempdb. It is possible to check for existence, but that is the only time I have ever referenced tempdb directly. Simply use your temp table name. Example below of checking for existence
IF OBJECT_ID('TempDB.dbo.#DuplicateAssignments') IS NOT NULL
BEGIN
DROP TABLE #DuplicateAssignments
END
You name temp tables by prefacing the name with # (for local tables the ones you would use 999.9% of the time) and ## for global temp tables, then the rest of the name you want.
There's a few MSDN articles that are probably the best source of information on the tempDB database in SQL Server.
tempdb Database
The tempdb system database is a global
resource that is available to all
users connected to the instance of SQL
Server and is used to hold the
following:
Temporary user objects that are explicitly created, such as: global or
local temporary tables, temporary
stored procedures, table variables, or
cursors.
Internal objects that are created by the SQL Server Database Engine, for
example, work tables to store
intermediate results for spools or
sorting.
Row versions that are generated by data modification transactions in a
database that uses read-committed
using row versioning isolation or
snapshot isolation transactions.
Row versions that are generated by data modification transactions for
features, such as: online index
operations, Multiple Active Result
Sets (MARS), and AFTER triggers.
Operations within tempdb are minimally
logged. This enables transactions to
be rolled back. tempdb is re-created
every time SQL Server is started so
that the system always starts with a
clean copy of the database. Temporary
tables and stored procedures are
dropped automatically on disconnect,
and no connections are active when the
system is shut down. Therefore, there
is never anything in tempdb to be
saved from one session of SQL Server
to another. Backup and restore
operations are not allowed on tempdb.
There's also tempdb and Index Creation, this blog post along with Working with tempdb in SQL Server 2005 which states:
The SQL Server system database, tempdb, has undergone a number of changes in SQL Server 2005. There are new tempdb usages and internal optimizations in SQL Server 2005; tempdb architecture is mostly unchanged since SQL Server 2000.
The tempdb system database is very similar to a user database. The main difference is that data in tempdb does not persist after SQL Server shuts down.
The temporary tables created in TempDB are dropped when the query is completed.
I'm not sure on this (I would have to try it), but I think theoretically ALL tables created in TempDB are visible, although only the user that created the table has permission to access it.