Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MS SQL Server 2005, what happens when a temp table is being accessed by different executions of the same SP?

I have a stored procedure that first checks for a temp table (#temp_table), deletes it if it exists, uses the table, then finally drops it when it's done. This SP is called randomly when a user does something to trigger it and it is likely that sometimes the SP will be executed at the same time - or with some overlap.

Lets say I have Exec1 and Exec2 both of the same SP creating, altering, and dropping the #temp table, and they are running within milliseconds of each other.

What happens? Will Exec1 lock the #temp_table and Exec2 waits while Exec1 finishes? That would obviously be desirable in my case. I wouldn't want both Exec1 & 2 to use the table at the sametime, nor would I want Exec2 fail because Exec1 is already using the table.

[EDIT] Should I just convert my temp table to a table variable?

like image 363
jreed121 Avatar asked Oct 29 '13 23:10

jreed121


People also ask

Can we access a temp table of one stored procedure from another stored procedure?

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."

Can local temporary tables be seen by another connection to the same database?

Local temporary objects (Tables and Stored Procedures) are completely safe from being seen by other sessions.

Are temp tables automatically dropped SQL?

If the session which has created the local temporary table is closed, the temporary table will be dropped automatically by SQL Server.

Can we use temp table in another stored procedure SQL Server?

Global Temporary Tables. Stored procedures can reference temporary tables that are created during the current session. Within a stored procedure, you cannot create a temporary table, drop it, and then create a new temporary table with the same name.


1 Answers

In sql server if you create a local temp table it is with a single # sign sql server uses a few under-score and some ID in the back end. Say you create a Temp table with the name #Temp sql server in temp db Creates a Table with name #Temp_______10912098 , every Temp table created in separate connections will have their on ID in the end of the name.


TempTables

These are all the Temp Tables Created in different Connections all has the name #Temp but are appended with some underscores and a unique id sql server uses to differentiate between them.

like image 178
M.Ali Avatar answered Oct 16 '22 10:10

M.Ali