Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using Table variables faster than temp tables

Am I safe to assume that where I have stored procedures using the tempdb to write a temporary table, I'd be better off switching these to table variables to get better performance?

like image 634
Neil Knight Avatar asked Nov 05 '22 06:11

Neil Knight


2 Answers

Temp tables are better in performance. If you use a Table Variable and the Data in the Variable gets too big, the SQL Server converts the Variable automatically into a temp table.

It depends, like almost every Database related question, on what you try to do. So it is hard to answer without more information.

So my answer is, try it and have a look at the execution plan. Use the fastest way with the lowest costs.

like image 193
dknaack Avatar answered Dec 17 '22 02:12

dknaack


@Table can be faster as there is less "setup time" since the object is in memory only.

@Tables have a lot of catches though.

You can have a primary key on a @Table but thats about it. Other indexes Clustered NonClustered for combinations of columns are not possible.

Also if your table is going to contain any real data volumes (more then about 200 maybe 1000 rows) then accessing the table will be slower. Especially when you will probably not have a useful index on it.

#Tables are a pain in procs as they need to be dropped when debugging, They take longer to create. and they take longer to setup as you need to add indexs as a second step. But if you have lots of data then its #tables every time.

Even in cases where you have less then 100 rows of data in a table you may still want to use #Tables as you can create a usefull index on the table.

In summary i use @Tables most of the time for the ease when doing simple proc etc. But anything that need to perform should be a #Table.

like image 33
Paul Spain Avatar answered Dec 17 '22 03:12

Paul Spain