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.
Related
I have a huge packages in PL/SQL which executed a delete command on a table A.
I want to determine the procedure responsible for this operation.
My idea is to create a trigger on this table to track the "file" and "line" of the deletion.
Is that possible in PL/SQL like in C++ or PHP through file and line macros.
Otherwise, Is it possible for a trigger to find the name of the stored procedure that deleted data?
Thanks.
Is this ongoing tracking of rows deleted, or just the occasional check of "Hmmm....a SQL deleted some rows, I wonder where it came from?". If it is the latter, you can get that from V$SQL which tracks the originating PLSQL module that issued the SQL. The columns are PROGRAM_ID and PROGRAM_LINE#.
If you need a full example, I've got one on my site
https://connor-mcdonald.com/2016/01/20/problematic-sql-plsql-is-your-friend/
If I call a stored procedure which recursively calls itself, I am wondering if #vars, #tables and ##tables have non-conflicting instance copies. I am guessing #vars and #tables are ok, but ## should create problems.
I think the question further expands as: When a sp calls itself, does it create a new session?
No, it does not. Variables are scoped to one level (so they are not visible to nested calls), #temp tables are scoped to the session, ##temp tables are scoped globally. There is no way in T-SQL to even create a new session (even EXEC creates a new batch, but not a new session). Well, you could create a scheduled job on the fly (or maybe use OPENROWSET with the local server), but that's cheating.
Be wary of creating temp tables in stored procedures that nest, though: you'll run into trouble if you're not careful. Specifically, per the docs:
A local temporary table created within a stored procedure or trigger
can have the same name as a temporary table that was created before
the stored procedure or trigger is called. However, if a query
references a temporary table and two temporary tables with the same
name exist at that time, it is not defined which table the query is
resolved against. Nested stored procedures can also create temporary
tables with the same name as a temporary table that was created by the
stored procedure that called it. However, for modifications to resolve
to the table that was created in the nested procedure, the table must
have the same structure, with the same column names, as the table
created in the calling procedure.
That means the "obvious" case where you create "the same" temp table in every step of the nesting works as you'd expect: every nested call has its "own" table and won't see the parent table. If you don't create the table in a nested call, though, you'll get the parent table, and if you create one with a different structure (for whatever reason) you can actually get a compilation error when SQL Server detects this bizarre set of circumstances.
You can therefore both use a temp table as way to keep state across calls, or specifically not do that by "recreating" it, but it's up to you to keep things sane.
All recursions are in the same batch
Each stored procedure (recursion) has it's own scope with in the batch
In simple terms
A connections has many batches (one after the other)
A batch has many scopes (each code unit such stored proc, function, etc)
So
#vars are scoped to that code unit = Ok per recursion
#tables are scoped to the connection = NOT Ok, visible to recursions
##tables are scoped to all using connections = NOT Ok, visible to recursions
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'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.
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.