Which one is better ?| Temp Table or Table Variable? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

Which one is better ?| Temp Table or Table Variable?

23rd Mar 2017, 6:54 AM
Akwin Lopez
Akwin Lopez - avatar
1 Resposta
0
As per my experience temp tables are better than table variables. The problem with the table variables is that query optimizer will generate bad/unpredictable query plans as they donā€™t have statistics on them. If you check the estimated number of rows then it will always be 1. DECLARE @tab AS TABLE ( ID INT ) INSERT INTO @tab SELECT TOP 100 [CustomerID] FROM [dbo].[CustomerInfo] SELECT ID FROM @tab As a general rule of thumb across many SQL SERVER communities is that if you have 1000 rows or less then go for table variable otherwise go for temp table. Well we can influence the query optimizer. One of the ways is given below- DECLARE @x AS INT = 100 DECLARE @tab AS TABLE ( ID INT ) INSERT INTO @tab SELECT TOP (@x) [CustomerID] FROM [dbo].[CustomerInfo] Table variables do not qualifying for parallelism thatā€™s why they are better suited for small amounts of data. Table Variables can write to the disk if threshold goes over a certain number of records. Table variables do write to the log file and they can have non clustered indexes if associated with a ā€˜NONCLUSTERED UNIQUEā€™ or ā€˜NONCLUSTERED PRIMARY KEYā€™ constraint.
23rd Mar 2017, 6:57 AM
Akwin Lopez
Akwin Lopez - avatar