Reputation: 3
When we use temporary table it gets created in another database tempdb which is a performance overhead. But if we create normal table in stored procedure in place of temp table then it will get created in its own database.
So my question is why we use temp tables in procedure?
Is that due to only the scope of the tables?
Upvotes: 0
Views: 1773
Reputation: 183
The prime this benifit is the simplicity in programming and managing. As you need not to code any thing to create the temp table, you can directly select into .... #tbl,
Secondly Dynamic isolation to the session, you need not to do any thing for session sharing avoidance. let say if same SP runs from two different session two isolated instance of the table would be created. Run the following code from 1 Query pad (management studio)
SELECT 'ASP.Net' subject INTO #test SELECT * FROM #test
and from other,
SELECT 'C #' subject INTO #test SELECT * FROM #test
would create two different instance of the table with table name not just #test but some thing like
now run the following query to realize it
USE TEMPDB
SELECT name FROM sys.tables WHERE name LIKE '#test%';
and
Further more clean up process is also taken care by Database.
Thanks and Regards,
Rk_Hirpara
Upvotes: 0
Reputation:
Any performance difference between creating a temporary table and creating the same table as a regular (not temporary) table is negligible. In fact, I would expect to see temp tables perform better as they are treated much like table variables (cache use, miminal locking output). For a really good discussion on temporary tables, I would go here. That article is a brilliant comparison between temp tables and table variables, which is very enlightening if you want to learn about temp tables and how they are handled.
Upvotes: 1
Reputation: 176
Here are a couple of reasons to use temporary or variable tables:
My preference for anything other than small data-sets would be to use a temporary table over a variable table because:
Upvotes: 0
Reputation: 239824
We use temp tables1 where we want to store a set of rows and work with them but do not want to interfere with any other instance of the same piece of code, running on a different connection.
If we worked with permanent tables, we'd have to do extra work to prevent interference (such as always filtering on @@SPID
) or have to restrict our code to only being executed by a single connection at a time.
We also benefit from automatic clean up when the temp table falls out of scope.
1Or table variables. They're much the same, just with different scoping rules.
Upvotes: 6