| Introduction Temporary Tables are a great T-SQL feature that lets you store and process intermediate results by using the same selection, update, and join capabilities that you can use with typical SQL Server tables. “In the early days when I used Access I used to create tables that I treated as temporary and then delete them whenever I finished my task”. Using SQL Server this is much simpler.” Types of Temporary Tables in SQL You can create two types of temporary tables in SQL, local and global temporary tables. The two types of temporary tables, local and global, differ from each other in their names, their visibility, and their availability. |
Local Temporary Tables
|
Global Temporary Tables
|
| For example: If you create a table named 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 you create a local temporary table named #employees, you are the only person who can work with the table, and it is deleted when you disconnect. If you create a global temporary table named ##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 when both of you disconnect. SQL statements for creating the temporary table using the CREATE TABLE statement: |
|
CREATE TABLE #MyTempTable (cola INT PRIMARY KEY) |
| When you create local or global temporary tables, the CREATE TABLE syntax supports constraint definitions with the exception of FOREIGN KEY constraints. If a FOREIGN KEY constraint is specified in a temporary table, the statement returns a warning message indicating that the constraint was skipped, and the table is still created without the FOREIGN KEY constraints. Temporary tables cannot be referenced in FOREIGN KEY constraints. |
Naming Of Temporary Tables Temporary tables are always created in tempdb. No matters it is created from the stored procedure internally or from the SQL Query Analyzer window. If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, SQL Server has to be able to distinguish the tables created by the different users. SQL Server does this by internally appending a numeric suffix to each local temporary table name. The full name of a temporary table as stored in the sysobjects table in tempdb consists of table name specified in the CREATE TABLE statement and the system-generated numeric suffix. To allow for the suffix, table_name specified for a local temporary name cannot exceed 116 characters. Reason: “Table names in SQL are the combination of owner.table_name and it must be unique within the database. Table_name can contain a maximum of 128 characters, except for local temporary table names (names prefixed with a single number sign (#)) that cannot exceed 116 characters.” For example: CREATE TABLE #Yaks (YakID int,YakName char(30)) SELECT Name FROM tempdb.dbo.sysobjects WHERE Name LIKE ‘#yak%’ The above select query will return the result something like below displayed. name ——————————————————————- #Yaks__________________________________________________00000000001D (1 row(s) affected) SQL Server stores temporary tables as a database object with a type of unique number appended on the end of the name. But in case of temporary tables it may be the possibility that two users can create the temporary table with the same name as we know that all temporary tables stored in the tempdb database, so if the name of both temporary tables will be same then SQL server will through an error to the user because objects name in the SQL server must be unique in the database. So, to avoid this problem whenever anyone creates any temporary table SQL server automatically appends a unique string with the table name that is given by user while creating the table, But don’t worry you need to do anything with this extra string, It does all this for you automatically. You just have to refer to your #table_name with which you have created the temporary table. You can refer this name anywhere in your code where you want. |
Deletion of Temporary Tables |
|
| For example: SQL statements for deleting the temporary table using the DROP TABLE statement: DROP TABLE #Table_name A local temporary table created within a stored procedure or trigger is distinct from a temporary table with the same name created before the stored procedure or trigger is called. |
Use of Temporary Table Temporary tables are used in several ways. Most commonly uses |
SQL Server cursors have huge overhead. Maintenance of code is much easier if you use temporary tables to the T-SQL. It will be much easier to debug your stored procedure when your using temporary tables as the data will be saved in temporary tables. |
Limitations of Temporary Tables Temporary tables are created in the tempdb database and create additional overhead for SQL Server, reducing overall performances. This happens because all reads and writes to the temporary tables are done within the tempdb database. |
Using Temporary Tables Effectively If you do not have any option other than to use temporary tables, use them effectively. There are few steps to be taken. |
|
| In general, temp tables should be avoided, if possible. Because they are created in the tempdb database, they will create additional overhead for SQL Server, slowing overall performance. As an alternative to temp tables, consider the following alternatives: |
It all depends on your requirement at that time when you are creating your query, but as written in Microsoft SQL Server Book Online, If you are using SQL Server 2000 or higher, you can take advantage of the new TABLE variable type. These are similar to temporary tables except with more flexibility and they always stay in memory. —————————————————————– INSERT INTO @TibetanYaks (YakID, YakName) SELECT YakID, YakName Table variables don’t need to be dropped when you are done with them. |
Which to use |
|
| Conclusion |
| Generally, temporary tables should be avoided as much as possible. If you need to use them follow the steps above so that you have the minimum impact on server performance. |
|
******* |
| Reference from and many thanks to following websites and articles: Microsoft’s Book Online For SQL Server 2000 Sql-Server-Performance Sql Server Central SqlTeam Prashant Pandey (TechAhead) |
SQL – Temporary Tables
September 27, 2007 by Prashant Pandey

This is very usefull information for all computer users n programmers.Prashant Rocks!!!
Hey!!
u are doing a gr8 work.
this one is useful place for all developers searching for latest .net/sql interview questions.
even for the beginners who want to grassp knowledge…
Best of luck dude…
continue with this good work.
Amit ………………..
thnx
it helped me very much
Hi rahul, thanks for your comment.. and tell you one thing .. good comments always boost my confidence.. but bad comments or suggestion are also invited caz they told me to make myself more perfect in that area..
I pleased that this article helps you, So keep visiting the blog for new and intresting topics..
Thank u very much for giving this much information.But will u add a little bit more about this
Hi Uday,
I think i covered all about temporary tables , wht i think… But as you know no one is perfect,
so tell me wht else i need to add in this article. tell me i’ll add it here,
Your suggestions are always welcome…
Hi Prashant,
Great work dude.Do more and more better next time..my best wishes are always with u.
Ravi Raghav
http://www.realitservices.com
Real IT services specialises in providing Web and Software Development solutions in terms of the requirements like IT Outsourcing,CRM,Business Process Outsourcing,Content Management System,Offshore Software Development,Website Promotion(SEO),Customer Software Development at an affordable cost with 100% customer satisfaction.To know more about our services
Go here http://www.realitservices.com
i need to have questionnumber as an identity (int)
in which my sp contains one parameter
like this
CREATE PROCEDURE spGetAnswerDescription1(@TestId int)
AS
create table #temptable
(QID int identity,
QuestionID int)
SELECT tbAnswers.QuestionID,tbQuestionPaper.QuestionDescription,tbAnswers.YourAnswer,tbanswers.CorrectAnswerDes,tbanswers.YourAnswerDes,
tbAnswers.AnswerDescription,tbQuestionPaper.ImagePath from tbQuestionPaper ,tbAnswers
where tbQuestionPaper.QuestionId=tbAnswers.QuestionId and tbQuestionPaper.TestID=@TestId
select * from #temptable
GO
when dis compiled i m getting an error tht i cant insert when identity_insert is OFF
when i create SP with no parameters its working accrately
plzz send me the solution
Great detail.
Is there ever a possibility of “name collision”, if the *same* user runs the same SP and two instances of the temp table are in existence at the same time?
Stored proc is being executed from a web app, if that means anything.
Thank you,
Steve
Hi steve,
its nice to hear that you like this article.
“Is there ever a possibility of “name collision”, if the *same* user runs the same SP and two instances of the temp table are in existence at the same time?
Stored proc is being executed from a web app, if that means anything.“
Now what i think is “yes there may be a possibility of name collision” i am not sure caz you are executing the SP from different web applications, but again the point is your sql server is same. So it may be arround 80% chances of name collision,
But to avoid this what you can do is DROP the temporary table from your sp using the following code
DROP TABLE #my_temp
So there will be very minor possibilities of name collison.
I’m discussing your topic further with some experts, so if will find anything special will let you know here.
Thanks,
keep visiting the blog.
Thanks Prashant. Because of the way the web app is designed, it is improbable that the same user will run the same SP simultaneously, but because the SP will get relatively heavy use it is possible, so I appreciate your follow up.
The #temp table however will have very few (less than 10 rows) so it’s lifetime should be quick and short.
Thanks again,
Steve
Thanks for your appreciation.
I said that there are chances of name collision because suppose if you have a sp which creates a temp table and use that, but remember its not deleting that table.
So in query analyzer window if you execute this sp twice then in the 2nd time you’ll get an error something like “#temp_table already exists” So by considering this point in the case of web app, there may be a possibilities of name collision, because all the queries executing in the same SQL server.
but as you said there are very few chances, but still there is 1% chance, So i thinks its better to drop temp tables if not used in any further query, because if u not delete these they will unnecessarily take the space in the SQL Server.
Thanks,
Thank you for you detailed example.
I need to take the example above one step further.
For Example, if I make a temporary table I then want to innerJoin this temp table to another table to retunr rows form the joined table.
This is my statment :
DECLARE @THEIDS TABLE (CONTRACT_ID bigint)
INSERT INTO @THEIDS (CONTRACT_ID)
SELECT CONTRACT_ID
FROM dbo.DOCUMENTS WHERE DOCUMENTS.DOCUMENT_ID > 100
GROUP BY CONTRACT_ID
SELECT * FROM @THEIDS
INNER JOIN CONTRACTS ON @THEIDS.CONTRACT_ID = CONTRACTS.CONTRACT_ID
If I remove the end from “INNER JOIN” it works fine, but this errors with a error :
“Must declare the variable ‘@THEIDS’.”
Note the Group By Clause this is why I’ve had to create a temp table.
Id it possible to create a temp table and then use it like this?
This is very usefull and clearfull article ever than others.
thanks for it…
CHIN.
Its really good infromation abt tempory tables gives clear cut idea abt that
Thanks lot!!!!!!!!!!!!!
thanks alot……… these are great information regarding to temporary tables…and really help to understand DB query optimization
Thank You, for this Detailed Guideline.
Good Job…Thanks
Hi,
I have a query regarding the nested SP’s and use of Global Temp Table in it.
The thing is I am calling SP2(lets say) from Sp1. This Sp2 is fetching multiple records from a table and these records needs to be sent back to SP1.
Now the problem here is can I define a GTT in SP1 and insert data in it in SP2 and again retrieve it in SP1.
If so can someone tell me how and what will be the syntax..
This is really a showstopper for me?
Immediate response is highly appreciated.
Hi Prashant,
You are doing a great job. The article is really very good.
I have a question. I have a stored procedure in which at the end of the stored procedure after all the necessary code is written the global temporary tables are dropped. Once the stored procedure is executed how do i view the data in the temporary tables to troubleshoot the errors. I was told to comment on the code where the global temporary tables are dropped, I commented it but I am unable to save the stored procedure with the changes as it already exists and could not accomplish my goal. So how do i view the data generated in the temporary table.
Any suggestions would be of great help.
Thanks
Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru
This is very up-to-date info. I’ll share it on Twitter.
Hi Prashant,
Do you still check these comments? If so, here is my question re the need for a temp table/table variable.
1) I want to get a result set of job numbers, maybe 20 of them.
2) Then–for each of those jobs–I want to append each job into a parent table, then retrieve it’s @@IDENTITY.
3) Then–for each job–using it’s @@IDENTITY, I want to append child records for that job into another table.
The way I’ve come up with is to retrieve my result set into a table variable, then a cursor to fetch each record, then do the appends for each record.
I could write a loop on the client and call the sproc 20 separate times by passing the job, but that seems inefficient.
Is there a better way to do this than the idea I had?
Thanks!
Hi @tk,
I think you, first fetch the job numbers data and run a while loop on this job_number data and insert parent records.
After that in the same loop fetch the PARENT ID from parent table on the basis of Job_number, and run another while loop on that data. if the job number is not present then you need to go with @@IDENTITY (but if the job number is not present I think you should check you’re database structure again for implementing proper relationships in between tables, so that fetching and insertion can be easy and faster)
WHILE LOOP is there in SQL and they are better in all aspects than CURSORS
Always prefer WHILE loops over CURSORS, both performs the same kind of functionality, whereas CURSORS are slow.
Checkout this article: http://techahead.wordpress.com/2007/10/27/sql-cursors/ in this I have tried my best to explain WHY cursors are slow and how to use WHILE loop as an alternative for CURSORS
I have a stored proc A, which creates a temporary table. Inside this stored proc, I have another stored proc B where I am inserting the values into the temp table. After the completion of stored proc B, I am doing a select *from #temptable in proc A. Since I have created the temp table in proc A, I shouldnt have any problems while doing a select query. Am I correct here??