I have a multi-user ASP.NET app running against SQL Server and want to have StoredProcA create a #temptable temp table - not a table variable - to insert some data, then branch to StoredProcB, StoredProcC, and StoredProcD to manipulate the data in #temptable per business rules.
The web app uses connection pooling when talking to SQL. Will I get a new #temptable scratch area for each call of StoredProcA? Or will the connection pooling share the #temptable between users?
Connection pooling (with any modern version of SQL Server) will call sp_reset_connection when reusing a connection. This stored proc, among other things, drops any temporary tables that the connection owns.
A ## table will be shared by all users. I assume this is not your intention.
A single-# temp table is visible to all stored procedures down the call stack, but not visible outside that scope. If you can have Proc A call B, C, and D, you should be OK.
Edit: The reporting procedure I should be working on right now is a lot like that. :) I create a temp table (#results) in the root proc that's called by the application, then do some complicated data mangling in a series of child procedures, to 1) abstract repeated code, and 2) keep the root procedure from running to 500+ lines.
#temptable doesn't survive past the end of the procedure in which it was declared, so it won't ever be seen by other users.
Edit: Heh, it turns out that the "nesting visibility" of temp tables has worked since SQL Server 7.0, but I never updated any of my code to take advantage of this. I guess I'm dating myself -- a lot of people probably can't imagine the hell that was SQL Server in the 6.0 and 6.5 days...
From the MS docs:
http://msdn.microsoft.com/en-us/library/ms177399(SQL.90).aspx
Temporary Tables
Temporary tables are similar to permanent tables, except temporary tables are stored in tempdb and are deleted automatically when they are no longer used.
There are two types of temporary tables: local and global. They differ from each other in their names, their visibility, and their availability. Local temporary tables have a single number sign (#) as the first character of their names; they are visible only to the current connection for the user, and they are deleted when the user disconnects from the instance of SQL Server.
Global temporary tables have two number signs (##) as the first characters of their names; they are visible to any user after they are created, and they are deleted when all users referencing the table disconnect from the instance of SQL Server.
For example, if you create the table employees, the table can be used by any person who has the security permissions in the database to use it, until the table is deleted. If a database session creates the local temporary table #employees, only the session can work with the table, and it is deleted when the session disconnects. If you create the global temporary table ##employees, any user in the database can work with this table. If no other user works with this table after you create it, the table is deleted when you disconnect. If another user works with the table after you create it, SQL Server deletes it after you disconnect and after all other sessions are no longer actively using it.
Additionally from Curt who corrected the error of my ways and just in case you miss the citation in the comment:
http://msdn.microsoft.com/en-us/library/ms191132.aspx
If you create a local temporary
table inside a stored procedure, the
temporary table exists only for the
purposes of the stored procedure; it
disappears when you exit the stored
procedure.
If you execute a stored procedure
that calls another stored procedure,
the called stored procedure can
access all objects created by the
first stored procedure, including
temporary tables.
To share a temp table between users use two hashes before the name ##like_this.
In this case, though make sure you take steps to avoid clashes with multiple instances of the program.
Temp tables get created with name mangling under the hood so there shouldn't be conflicts between different stored procedure calls.
If you need to manipulate the same temp data in subsequent stored procedure calls, it's best to just go with a real table and use some sort of unique identifier to make sure you are only dealing with relevant data. If the data is only valuable temporarily, manually delete it once you're done.
Related
I have a stored procedure which makes used of a temporary table with ##temp creating on the fly using select * into ##temp from tablename.
The problem I have having is this stored procedure seems to delete or make this available only for that moment in time when the query is ran, despite having ## which is global and can be used by other users from what i know.
I am using SSRS to pull the stored procedure and using drill through from this report to the same report, first one only showing charts, the second report which is the same stored procedure which uses the actions link via parameter but the second report doesn't recognize the ##temp table.
Now that you got the background, is there a way around this or a better way of doing it, keep in mind we don't have a data warehouse at the moment, so just using temporary tables to do the work around.
Thanks
From MSDN:
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 admin access to the server, try this answer.
I have a stored proc that creates a temp table. It is only needed for the scope of this stored proc, and no where else.
When I use temp tables list this, I always check to see if the temp table exists, and drop it if it does, before creating it in the stored proc. I.e.:
IF OBJECT_ID('tempdb..#task_role_order') IS NOT NULL
DROP TABLE #task_role_order
CREATE TABLE #task_role_order(...)
Most of the time, is it a best practice to drop the temp table when done with it, in addition to before creating the temp table?
If more context is needed, I have a .NET Web API back end that calls stored procs in the database. I believe that SQL server drops the temp table when the SQL Server session ends. But I don't know if .NET opens a new SQL Server session each time it queries the database, or only once per application lifecycle, etc.
I've read this similar question, but thought that it was slightly different.
Usually, it is considered a good practice to free up resource as long as you don't need it anymore. So I'd add DROP TABLE at the end of stored procedure.
Temporary table lives as long as connection lives. Usually, applications use connection pooling (it is configurable) and connection doesn't close when you call Connection.Close. Before connection re-usage, client executes special stored procedure (sp_reset_connection) which does all clean-up tasks. So temp tables will be dropped in any case, but sometimes after some delay.
It's very unlikely to be of much impact, but if I had to choose I would do neither. Temporary tables are accessible via nested stored procedures, so unless you have a specific need to pass data between procedures, not doing either will help avoid contention if you happen to use the same name, call a procedure recursively, in a circular manner (and it is valid), or you have another procedure that happens to use the same name and columns. Dropping it out of practice could hide some weird logic errors.
For example Proc A creates temporary table, then calls B. B drops and creates the table. Now either Proc A now is referencing the temporary table created, or since Proc A is not nested inside B, Proc A mysteriously fails. It would be better to have proc B fail when it tries to create the temp table.
At the end of the day SQL Server will clean these up, but it won't stop you from leaking between nested procedures.
I have a stored procedures that calls many other stored procedures and I would like to log intermediary results after each SP executed.
Is it any other better option that using a local or global temporary table and to insert rows in that table? I'm thinking it is not so good if the initial SP is executed in parallel by different users.
I would log directly into a physical table, but for the kind of volume you are looking at a tmp table wouldn't strain anything much either.
This comment changes my answer.
"I don't need a history, I just need to return a single result set so it can be binded to a grid"
Absolutely use a local temp table, do not worry about side by side calls in this case.
create a session table in the main sp and log all the calls as you wish and at the end move it to a physical table with an ID to identify
What is best practice for handling the dropping of a temp table. I have read that you should explicitly handle the drop and also that sql server should handle the drop....what is the correct method? I was always under the impression that you should do your own clean up of the temp tables you create in a sproc, etc. But, then I found other bits that suggest otherwise.
Any insight would be greatly appreciated. I am just concerned I am not following best practice with the temp tables I create.
Thanks,
S
My view is, first see if you really need a temp table - or - can you make do with a Common Table Expression (CTE). Second, I would always drop my temp tables. Sometimes you need to have a temp table scoped to the connection (e.g. ##temp), so if you run the query a second time, and you have explicit code to create the temp table, you'll get an error that says the table already exists. Cleaning up after yourself is ALWAYS a good software practice.
EDIT: 03-Nov-2021
Another alternative is a TABLE variable, which will fall out of scope once the query completes:
DECLARE #MyTable AS TABLE (
MyID INT,
MyText NVARCHAR(256)
)
INSERT INTO
#MyTable
VALUES
(1, 'One'),
(2, 'Two'),
(3, 'Three')
SELECT
*
FROM
#MyTable
CREATE TABLE (Transact-SQL)
Temporary tables are automatically dropped when they go out of scope, unless explicitly dropped by using DROP TABLE:
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.
All other local temporary tables are dropped automatically at the end of the current session.
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.
I used to fall into the crowd of letting the objects get cleaned up by background server processes, however, recently having issues with extreme TempDB log file growth has changed my opinion. I'm not sure if this has always been the case with every version of SQL Server, but since moving to SQL 2016 and putting the drives on a PureStorage SSD array, things run a bit differently. Processes are typically CPU bound rather than I/O bound, and explicitly dropping the temp objects results in no issues with log growth. While I haven't dug in too deeply as to why, I suspect it's not unlike garbage collection in the .NET world where it's synchronous when called explicitly and asynchronous when left to the system. This would matter because the explicit drop would release the storage in the log file, and make it available at the next log backup, whereas this appears to not be the case when not explicitly dropping the object. On most systems this is likely not a big issue, but on a system supporting a high volume ERP and web storefront with many concurrent transactions, and heavy TempDB use, it has had a big impact. As for why to create the TempDB objects in the first place, with the amount of data in most of the queries, it would spill over into TempDB storage anyway, so it's usually more efficient to create the object with the necessary indexes rather than let the system handle it automatically.
In a multi-threaded scenario where each thread creates its own set of tables and the number of threads is throttled, not dropping your own tables means that the governor will consider your thread done and spawn more threads... however the temp tables are still around (and thus the connections to the server) thus you'll exceed the limits of your governor. if you manually drop the temp tables then the thread doesn't finish until they've been dropped and no new threads are spawned, thus maintaining the governor's ability to keep from overwhelming the SQL engine
As per my view. No need to drop temp tables explicitly. SQL server will handle to drop temp tables stored in temp db in case of shorage of space to process query.
I'm using SQL Server 2000, and many of the stored procedures it use temp tables extensively. The database has a lot of traffic, and I'm concerned about the thread-safety of creating and dropping temp tables.
Lets say I have a stored procedure which creates a few temp tables, it may even join temp tables to other temp tables, etc. And lets also say that two users execute the stored procedure at the same time.
Is it possible for one user to run the sp and which creates a temp table called #temp, and the another user runs the same sp but gets stopped because a table called #temp already exists in the database?
How about if the same user executes the same stored procedure twice on the same connection?
Are there any other weird scenarios that might cause two users queries to interfere with one another?
For the first case, no, it is not possible, because #temp is a local temporary table, and therefore not visible to other connections (it's assumed that your users are using separate database connections). The temp table name is aliased to a random name that is generated and you reference that when you reference your local temp table.
In your case, since you are creating a local temp table in a stored procedure, that temp table will be dropped when the scope of the procedure is exited (see the "remarks section").
A local temporary table created in a stored procedure is dropped automatically when the stored procedure completes. 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 which called the stored procedure that created the table.
For the second case, yes, you will get this error, because the table already exists, and the table lasts for as long as the connection does. If this is the case, then I recommend you check for the existence of the table before you try to create it.
Local-scope temp tables (with a single #) are created with an identifier at the end of them that makes them unique; multiple callers (even with the same login) should never overlap.
(Try it: create the same temp table from two connections and same login. Then query tempdb.dbo.sysobjects to see the actual tables created...)
Local temp tables are thread-safe, because they only exist within the current context. Please don't confuse context with current connection (from MSDN: "A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished"), the same connection can safely call two or more times a stored procedure that creates a local temp table (like #TMP).
You can test this behavior by executing the following stored procedure from two connections. This SP will wait 30 seconds so we can be sure the two threads will be running their over their own versions of the #TMP table at the same time:
CREATE PROCEDURE myProc(#n INT)
AS BEGIN
RAISERROR('running with (%d)', 0, 1, #n);
CREATE TABLE #TMP(n INT);
INSERT #TMP VALUES(#n);
INSERT #TMP VALUES(#n * 10);
INSERT #TMP VALUES(#n * 100);
WAITFOR DELAY '00:00:30';
SELECT * FROM #TMP;
END;
The short answer is:
Isolation of temporary tables is guaranteed per query, and there's
nothing to worry about either in regard to threading, locks, or
concurrent access.
I'm not sure why answers here talk about a significance of 'connections' and threads as these are programming concepts, whereas query isolation is handled at the database level.
Local temporary objects are separated by Session in SQL server. If you have two queries running concurrently, then they are two completely separate sessions and won't intefere with one another. The Login doesn't matter, so for example if you are using a single connection string using ADO.NET (meaning that multiple concurrent queries will use the same SQL server 'login'), your queries will all still run in separate sessions. Connection Pooling also doesn't matter. Local temporary objects (Tables and Stored Procedures) are completely safe from being seen by other sessions.
To clarify how this works; while your code has a single, common name for the local temporary objects, SQL Server appends a unique string to each object per each session to keep them separate. You can see this by running the following in SSMS:
CREATE TABLE #T (Col1 INT)
SELECT * FROM tempdb.sys.tables WHERE [name] LIKE N'#T%';
You will see something like the following for the name:
T_______________00000000001F
Then, without closing that query tab, open up a new query tab and paste in that same query and run it again. You should now see something like the following:
T_______________00000000001F
T_______________000000000020
So, each time your code references #T, SQL Server will translate it to the proper name based on the session. The separation is all handled auto-magically.
Temp tables are tied to the session, so if different users run your procedure simultaneously there's no conflict...
Temp tables are created only in the context of the query or proc that creates them. Each new query gets a context on the database that is free of other queries' temp tables. As such, name collision is not a problem.
If you look in the temps database you can see the temporary tables there, and they have system generated names. So other than regular deadlocks you should be OK.
unless you use two pound signs ##temp the temp table will be local and only exists for that local connection to the user
First let's make sure you are using real temp tables, do they start with # or ##? If you are creating actual tables on the fly and then dropping and recreating them repeatedly, you will indeed have problems with concurrent users. If you are createing global temp tables (ones that start with ##) you can also have issues. If you do not want concurrency issues use local temp tables (They start with #). It is also a good practice to explicitly close them at the end of the proc (or when they are no longer needed by the proc if you are talking long multi-step procs) and to check for existence (and drop if so) before creating.