Saturday 21 December 2013

Biggest difference between Table variables & Temp tables in Sql Server


BEGIN TRAN
declare @Test_var table
(
id int, data varchar(20)
)
create table #temp_table
(
id int, data varchar(20)
)
insert into @Test_var
select 1, 'data 1' union all
select 2, 'data 2' union all
select 3, 'data 3'
insert into #temp_table
select 1, 'data 1' union all
select 2, 'data 2' union all
select 3, 'data 3'
select * from #temp_table
select * from @Test_var
ROLLBACK
select * from @Test_var


/*
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.

No comments:

Post a Comment