Thursday, January 20, 2011

SQL-Temp Table And Table Variable

What are the difference between the use of a SQL "Temporary Table" and "Table Variable"? Well lets take a look...
Temporary Table
The first thing to note is a "Temporary Table" is valid for a whole session. Here is a query you can try out to see the scope of where the "Temporary Table" exists...\/\/\/
 create table #tmpTable(i int)  
 insert into #tmpTable select 345
 Go  
 create table #tmpTable(i int)  
 insert into #tmpTable select 345  
 Go  
As you can see by executing the above query it will come up with an error. Your are still in the same session scope that the first "#tmpTable" was still in the database. The only way to make another Temporary Table in the same session is to "Drop Table <table name>" or completely exit out of the current session to get rid of saved temporary table. Also it is possible to add columns or records to a Temporary Table.

Table Variable
Here is a query you can try out to see the scope of where the "Temporary Table" exists...\/\/\/
 declare @varTable table(i int)  
 insert into @varTable select 45  
 GO  
 declare @varTable table(i int)  
 insert into @varTable select 45  
 GO  
If you executed the query you would find that you would not get an error when executing. This is because a "Table Variable" has a statement-level scope, as soon as the statement is executed the scope is lost, and also the declared "Table Variable". Different from a "Temporary Table" in that you cant really alter the "Table Variable".

More to come, CA.

No comments:

Post a Comment