Temporary table VS table variables: suitable for use (1)

Source: Internet
Author: User

Temporary table VS table variables: suitable for use (1)

For a long time, there has been a lot of debate over the advantages and disadvantages of temporary tables and table variables. Some friends in the Technical Group even think that table variables are almost useless, such as no statistical information or transactions. but this is not the case. here I will make a comparison between the temporary table and the table variables, and describe in detail where most people do not understand or have ambiguity.

Note: Only temporary tables are discussed here.

Lifecycle

Temporary table: in session, In proc, or using explicit drop

Table variable: in batch

Here, a simple code is used to describe the scope of table variables.

 
 
  1. DECLARE @ t TABLE (I int) ---- Define TABLE variable @ t
  2.  
  3. SELECT * FROM @ t ----- access OK
  4.  
  5. Insert into @ t select 1 ----- insert data OK
  6.  
  7. Select * from @ t ------- access OK
  8. Go ------- end Batch Processing
  9. Select * from @ t ------- error in out-of-scope

Note: Although sqlserver does not allow you to use the Defined variables before defining the table variables, you can still run normally in the following situations!

 
 
  1. If 'A' = 'B'
  2. Begin
  3. DECLARE @ t TABLE (I int)
  4. End
  5. SELECT * FROM @ t ----- still accessible!

Log Mechanism

Both temporary tables and table variables are logged in tempdb.

The difference is that the active logs of the temporary table cannot be truncated before the transaction is completed.

Note that table variables do not support truncate, so temporary tables have obvious advantages when the object result set is completely cleared, while table variables can only be deleted.

Transaction support

Temporary table: supported

Table variable: not supported

We use simple examples to describe

 
 
  1. create table #t (i int)  
  2. declare @t table(i int)  
  3.  
  4. BEGIN TRAN ttt  
  5. insert into #t select 1  
  6. insert into @t select 1  
  7. SELECT * FROM #t  ------returns 1 rows  
  8. SELECT * FROM @t  ------returns 1 rows  
  9. ROLLBACK tran ttt  
  10.  
  11. SELECT * FROM #t    -------no rows  
  12. SELECT * FROM @t    -------still 1 rows  
  13. drop table #t       ----no use drop @t in session 

Select)

The temporary table will add the IS (intention sharing) lock to the relevant object.

The table variable adds the SCH-S (schema share) lock to the relevant object (equivalent to adding the nolock hint)

It can be seen that although the impact of the lock range IS different, but because the scope IS only session or batch, temporary table IS lock although the compatibility IS not as good as the SCH-S of the table variables, but the vast majority of the situation basically no impact.

If you are interested, you can use TF1200 for testing.

Index support

Temporary table support

Table variable conditions supported (only SQL2014)

In sql2014, you can create Index 1-1 while creating a table.

Note: Before sql2014, only one default uniqueness constraint can be created for table variables.

Cod

 
 
  1. DECLARE @t TABLE   
  2. (  
  3. col1 int index inx_1 CLUSTERED,   
  4. col2 int  index index_2 NONCLUSTERED,  
  5.        index index_3 NONCLUSTERED(col1,col2)  

Figure 1-1

 
 
  1. CREATE FUNCTION TVP_Customers (@cust nvarchar(10))  
  2. RETURNS TABLE 
  3. AS 
  4.  RETURN 
  5.  (SELECT RowNum, CustomerID, OrderDate, ShipCountry  
  6.  FROM BigOrders  
  7.  WHERE CustomerID = @cust);  
  8. GO  
  9. CREATE FUNCTION TVF_Customers (@cust nvarchar(10))  
  10. RETURNS @T TABLE (RowNum int, CustomerID nchar(10), OrderDate date,  
  11.  ShipCountry nvarchar(30))  
  12. AS 
  13. BEGIN 
  14.  INSERT INTO @T  
  15.   SELECT RowNum, CustomerID, OrderDate, ShipCountry  
  16.   FROM BigOrders  
  17.   WHERE CustomerID = @cust  
  18.   RETURN 
  19. END;  
  20.  
  21. DBCC FREEPROCCACHE  
  22. GO  
  23. SELECT * FROM TVF_Customers('CENTC');  
  24. GO  
  25. SELECT * FROM TVP_Customers('CENTC');  
  26. GO  
  27. SELECT * FROM TVF_Customers('SAVEA');  
  28. GO  
  29. SELECT * FROM TVP_Customers('SAVEA');  
  30. GO  
  31.  
  32. select b.text,a.execution_count,a.* from sys.dm_exec_query_stats a  
  33. cross apply sys.dm_exec_sql_text(a.sql_handle) b  
  34. where b.text like '%_Customers%' 

Figure 1-2

Other aspects

Table variables do not support select into, alter, truncate, dbcc, etc.

Table variables do not support table hint such as (force seek)

Execution Plan Estimation

I think this may be the reason for a strong debate on the method used. Because the table variables do not have statistical information and indexes cannot be added, you may sneer at the performance of the table variables in the execution plan, but what is the actual situation? In-depth analysis is required.

I will not describe the estimation of temporary tables here, but mainly describe the estimation of table variables in detail.

One reason for the introduction of table variables in sql2000 is to reduce re-compilation during some execution processes. for better performance. of course, the benefits will also bring some drawbacks. because it does not involve recompilation, the optimizer does not know the specific number of rows in the table variables. At this time, he adopted a conservative estimation method: the estimated number of rows is one row. 2-1

Code

 
 
  1. Declare @ t table (I int)
  2. Select * from @ t ----- at this time, the estimated number of rows in line 0 is 1
  3. Insert into @ t select 1
  4. Select * from @ t ----- at this time, 1 row, the estimated number of rows is still 1 row
  5. Insert into @ t values (2), (3), (4), (5), (6), (7), (8), (9 ), (10), (11), (12), (14), (15), (16), (17), (18), (19), (20)
  6. Select * from @ t ---- at this time, 19 rows, the estimated number of rows is still 1
  7.  
  8. --... No matter how many rows exist in the actual @ t, it is estimated to be 1 line because there is no re-compilation.

Figure 2-1

So when we add the re-compilation operation, the optimizer will know the specific number of rows of table variables. 2-2

Code

 
 
  1. Declare @ t table (I int)
  2. Select * from @ t option (recompile) ----- at this time, the estimated number of rows in row 0 is 1.
  3. Insert into @ t select 1
  4. Select * from @ t option (recompile) ----- at this time, 1 row, the estimated number of rows is 1 row
  5. Insert into @ t values (2), (3), (4), (5), (6), (7), (8), (9 ), (10), (11), (12), (14), (15), (16), (17), (18), (19), (20)
  6. Select * from @ t option (recompile) ---- 19 rows at this time, and the estimated number of rows is 19
  7. --... When hint is added, the optimizer will know the number of rows of table variables.

Figure 2-2

Now, we can see that the optimizer knows the number of rows in the table variables. in this way, in the process of table variable scanning, especially when the data volume is large, it will not cause some problems because the prediction is always 1.

If you just know the estimation principle and the existing code is re-compiled, you can imagine the workload. Here we will introduce a new Trace tag, Trace Flag 2453.

TF2453 can replace Hint for a certain extent, but only in the case of a simple trivial plans)

Note: TF2453 only applies to patches in sql2012 SP2 and SQL2014.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.