0
Which one is better ?| Temp Table or Table Variable?
1 ответ
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.