The Complete Guide to Temporary Tables and Table Variables Guy Glantser
Copyright © 2019 Madeira Ltd All Rights Reserved Full rights, including copyrights, belong exclusively to Madeira Ltd No use of the materials, in any form, is allowed, unless receiving a prior written permission from Madeira Ltd
A Few Words about Me… Name: Guy Glantser Email Address: guy@madeiradata.com Twitter: @guy_glantser Blog: www.linkedin.com/in/glantser Podcast: www.sqlserverradio.com Image courtesy of Mister GC / FreeDigitalPhotos.net
First, a Basic Comparison… Temporary Table Table Variable Storage tempdb Scope Session Batch Constraints Yes
First, a Basic Comparison… Temporary Table Table Variable Indexes Yes Statistics Yes No Recompilations Yes No
First, a Basic Comparison… Temporary Table Table Variable T-Log Footprint Full Minimal Table Parameters No Yes Parallelism Yes No
The Big Question: When to Use What?
Image courtesy of Stuart Miles / FreeDigitalPhotos.net
Bottom Line If the batch is executed only once in a while Use a temporary table with OPTION (RECOMPILE)
Bottom Line If not (the batch is executed many times per second) If the number of rows in the table is relatively fixed Use a temporary table
Bottom Line If the number of rows in the table varies all the time If performance with a temporary table is acceptable (due to recompiles) Use a temporary table
Bottom Line If performance with a temporary table is not acceptable If performance with a table variable is acceptable Use a table variable
Bottom Line If performance is not acceptable either way Try a hybrid solution
Bottom Line When using a table-valued parameter Consider using trace flag 2453
Image courtesy of David Castillo Dominici / FreeDigitalPhotos.net
Keep in Touch… Name: Guy Glantser Email Address: guy@madeiradata.com Twitter: @guy_glantser Blog: www.linkedin.com/in/glantser Podcast: www.sqlserverradio.com Image courtesy of Mister GC / FreeDigitalPhotos.net