I want some Moore

Blog about stuff and things and stuff. Mostly about SQL server and .Net
posts - 176, comments - 1796, trackbacks - 33

My Links

SQLTeam.com Links

News

Hi! My name is 
Mladen Prajdić  I'm from Slovenia and I'm currently working as a .Net (C#) and SQL Server developer. I'm a MCP and MCTS for SQL Server. I also speak at local user group meetings and conferences like NT Conference 
Welcome to my blog.

Search this Blog

My Blog Feed via Email


Users Online: who's online

Article Categories

Archives

Post Categories

Cool software

Other Blogs

Other stuff

SQL stuff

Biggest difference between Temp tables and Table variables in Sql Server

We've all heard about differences between temporary tables and table variables in SQL Server.

They include performance, storage in memory or disk, tempdb use, etc.

 

But the biggest and mostly overlooked difference is:

Table variables are Transaction neutral. They are variables and thus aren't bound to a transaction.

Temp tables behave same as normal tables and are bound by transactions.

 

A simple example shows this difference quite nicely:

 

BEGIN TRAN
declare @var table (id int, data varchar(20) )
create table #temp (id int, data varchar(20) )

insert into @var
select 1, 'data 1' union all
select 2, 'data 2' union all
select 3, 'data 3'

insert into #temp
select 1, 'data 1' union all
select 2, 'data 2' union all
select 3, 'data 3'

select * from #temp
select * from @var

ROLLBACK

select * from @var
if object_id('tempdb..#temp') is null
    select '#temp does not exist outside the transaction'

 

We see that the table variable still exists and has all it's data unlike the temporary table that doesn't exists when the transaction rollbacked.

 

This little known fact can be very handy in a bunch of different scenarions.

I showed one with auditing here.

 

kick it on DotNetKicks.com

Print | posted on Sunday, May 13, 2007 5:11 PM

Feedback

# re: Biggest difference between Temp tables and Table variables in Sql Server

good one
12/30/2007 11:15 AM | Sanjiv

# re: Biggest difference between Temp tables and Table variables in Sql Server

Superb Explanation...
7/18/2008 12:11 PM | mouli

# re: Biggest difference between Temp tables and Table variables in Sql Server

very good explanation
10/13/2008 3:55 PM | Thanigainathan S

# re: Biggest difference between Temp tables and Table variables in Sql Server

Nice Example
12/17/2008 5:58 AM | Sivakumar

# re: Biggest difference between Temp tables and Table variables in Sql Server

Really a good and helpful explanation. Keep going.
3/5/2009 10:50 AM | Raghu

# re: Biggest difference between Temp tables and Table variables in Sql Server

Very well explained
4/10/2009 7:03 AM | Barnana

# re: Biggest difference between Temp tables and Table variables in Sql Server

Ultimate example.....
4/25/2009 11:56 AM | KK

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 7 and 2 and type the answer here:

Powered by: