Temp Table usuage in a Multi User Environment - sql

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.

Related

SQL Server temp table check performance

IF OBJECT_ID('tempdb..#mytesttable') IS NOT NULL
DROP TABLE #mytesttable
SELECT id, name
FROM
INTO #mytesttable mytable
Question: is it good to check temp table existence (e.g: OBJECT_ID('tempdb..#mytesttable') ) when I first time create this temp table inside a procedure?
What will be the best practice in terms of performance?
It is good practice to check if table exists or not. and it doesn't have any performance impact. anyhow, temp tables automatically drops once procedure execution completes in sql server. sql server appends unique num with temp table name. so if same procedure executes more than once at same time also , it will not cause any issue. it depends on session. all procs executions have different session.
Yes, it is a good practice. I am always doing this at the beginning of the routine. In SQL Server 2016 + objects can DIE (Drop If Exists), so you can simplify the call:
DROP TABLE IF EXISTS #mytesttable;
Also, even at the end of the routine you temporary objects are destroyed and even the SQL Engine gives unique names to temporary tables, there is still another behavior to consider.
If you are naming your temporary table with same name, when nested procedure calls are involved (one stored procedure calls another) it is possible to get an error or corrupt your data. This is due to the fact that temporary table are visible in the current execution scope - so, #table in one procedure will be visible in the second called procedure (so you can modify its data or drop it).

How Temp Table works in Stored Procedures (global & local )

Image #1: I am creating a stored procedure for inserting records into #t1.
In the same session I am executing the Localtemp1 stored procedure for any number of times, and it works fine:
Image #2: again executing the stored procedure in another session & works fine as well:
Image #3: now creating stored procedure for inserting records into ##tt. For the first execution of globaltemp1 stored procedure, it works well:
Image #4: but when I executed it a second time, it is showing errors (does not exist in DB):
Image #5: then I closed the session where globaltemp stored procedure was created, and in a new session, I executed the stored procedure, and it works well for the first time:
Image #6: but when I execute it a second time, again it is showing errors (does not exist in DB):
What I know is scope of local temp & global temp, but in stored procedures, they were completely different
Can someone tell me
Execution of localtemp1 stored procedure for many times gives output but while executing globaltemp1 sp for the first time gives output and second time results in an error
As far as I know, after execution of stored procedure temptable gets dropped. Then why localtemp1 stored procedure is getting executed across all sessions and many number of times?
Why globaltemp1 stored procedure is executing once and for second time showing an error?
Final one, Globaltemp stored procedure shows output in another session for the first time only when created session was closed
I mean
56 ----> globaltemp sp was created
57 ----> to get o/p i need to close 56
58 ----> to get o?p i need to close 57 ( WHY ??? )
I am a beginner at SQL and please, someone make me understand because if I don't find logic & correct reason I could not dive into another topic.
The concept of temp table is to hold records temporarily. It's some kind of an array where you can store multiple records using the same variable.
When you create a Temp Table, actually it is being created in the tempdb of the corresponding server. Even if you are naming it as just #temp, the name on which it was created on the tempdb will be having some additional parameters like your database name from which the table was created and your session id etc.
I just created the following temp table in my master database
and this is how it was named in the tempdb
still, in my database, I can access it using the name #temp. But The limitation of such temp table is that they are local and can be accessed only from that session, So if I try to access this #temp from any other Query Window (Session) even on the same database, I won't be able to access it. That's where we use Global temp tables. So If I add one more # to the table name then it becomes global temp table which can be accessed across the sessions. It is still created on the Tempdb but like this
Whenever you close the query window/session both Local and Global temp tables are automatically dropped.
So in the case of stored procedures, the starting and ending time of the sp is treated as one session. So once the sp execution is completed all the temp tables created inside that sp is dropped. So you can not use one temp table that was created by one SP in another one.
Hope this helps
Local temporary tables are visible only in the current session, and global temporary tables are visible to all sessions. Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended.
If you have absolutely have to have a global temp table available your best solution would be to create a permanent table and then drop the table at the end of the stored procedure. You can check for it's existence before creating it:
IF OBJECT_ID('dbo.yourtablenamehere', 'U') IS NOT NULL
DROP TABLE dbo.yourtablenamehere;
The differences between a temp table and a permanent table are really not that much different, mostly that the temp table drops automatically. If you are using this in an application that is calling this procedure, it might be best to have the application load the temp table into array and do the comparisons for you since it can maintain the array while executing and re-executing stored procs.
There is a good reason to write to a temp table instead of creating a table then dropping it... access rights. If you are creating tables to be used by people who are only granted read only privileges, they will not be able to create the table.

Stored procedures and the use of temporary tables within them?

I know basic sql commands, and this is my first time working with stored procedures. In the stored procedure I am looking at, there are several temporary tables.
The procedure, is triggerred every morning, which then pulls a specific ID and then loops through each ID to grab certain parameters.
My question is: are temporary tables used in stored procedures so that when the procedure goes off the variables will be instantly passed into the parameters and loop, and then the temporary tables will be cleared, thus restarting the process for the next loop?
Temporary tables are used because as soon as the session that created them (or stored procedure) is closed the temporary table is gone. A Temp table with a single # in front of the name (also called a local temp table) is only visible in the session it was created in so a temp table with the same name can be created in multiple sessions without bumping into each other (SQL Server adds characters to the name to make it unique). If a temp table with two ## in front of it is created (a global temp table) then it is unique within SQL Server so other sessions can see it. Temp tables are the equivalent of a scratch pad. When SQL Server is restarted all temp tables and their values are gone. Temp tables can have indexes created against them and SQL Server can use statistics on Temp tables to create efficient query plans.
For stored procedures (SPs), they are the least restricted and most capable objects, for example:
Their usual alternatives, views and functions, are not allowed to utilize many things, like DML statements, temp. tables, transactions, etc.
SPs can avoid returning result sets. They also can return more than one result set.
For temp. tables:
Yes, once the SP is done, the table disappears along with its
contents (at least for single-# tables).
They have advantages &
disadvantages compared to their alternatives (actual tables, table
varaibles, various non-table solutions).
Stored Procedures, in my opinion, don't forcibly need Temporary tables. It's up to the SP's scope to decide if using a TempTable is the best approach.
For example, let's suppose that we want to retrieve a List of elements that come out from joining a few tables, then it's the best to have a TempTable to put the joined fields. On the other hand, if we're using a Stored Procedure to retrieve a single or field, I don't see the need for a Temp table.
Temp tables are only available during the usage of the Stored Procedure, once it's finished, the table goes out of scope.

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.

When to use temporary table in SQL Server 2005

I read about temporary tables, global temporary tables and table variables. I understood it but could not imagine a condition when I have to use this. Please elaborate on when I should use the temporary table.
Most common scenario for using temporary tables is from within a stored procedure.
If there is logic inside a stored procedure which involves manipulation of data that cannot be done within a single query, then in such cases, the output of one query / intermediate results can be stored in a temporary table which then participates in further manipulation via joins etc to achieve the final result.
One common scenario in using temporary tables is to store the results of a SELECT INTO statement
The table variable is relatively new (introduced in SQL Server 2005 - as far as i can remember ) can be used instead of the temp table in most cases. Some differences between the two are discussed here
In a lot of cases, especially in OLTP applications, usage of temporary tables within your procedures means that you MAY possibly have business processing logic in your database and might be a consideration for you to re-look your design - especially in case of n tier systems having a separate business layer in their application.
The main difference between the three is a matter of lifetime and scope.
By a global table, I am assuming you mean a standard, run of the mill, table. Tables are used for storing persistent data. They are accessible to all logged in users. Any changes you make are visible to other users and vice versa.
A temporary table exist solely for storing data within a session. The best time to use temporary tables are when you need to store information within SQL server for use over a number of SQL transactions. Like a normal table, you'll create it, interact with it (insert/update/delete) and when you are done, you'll drop it. There are two differences between a table and a temporary table.
The temporary table is only visible to you. Even if someone else creates a temporary table with the same name, no one else will be able to see or affect your temporary table.
The temporary table exists for as long as you are logged in, unless you explicitly drop it. If you log out or are disconnected SQL Server will automatically clean it up for you. This also means the data is not persistent. If you create a temporary table in one session and log out, it will not be there when you log back in.
A table variable works like any variable within SQL Server. This is used for storing data for use in a single transaction. This is a relatively new feature of TSQL and is generally used for passing data between procedures - like passing an array. There are three differences between a table and a table variable.
Like a temporary table, it is only visible to you.
Because it is a variable, it can be passed around between stored procedures.
The temporary table only exists within the current transaction. Once SQL Server finishes a transaction (with the GO or END TRANSACTION statements) or it goes out of scope, it will be deallocated.
I personally avoid using temporary tables and table variables, for a few reasons. First, the syntax for them is Microsoft specific. If your program is going to interact with more than one RDBMS, don't use them. Also, temporary tables and table variables have a tendency to increase the complexity of some SQL queries. If your code can be accomplished using a simpler method, I'd recommend going with simple.