Using with vs declare a temporary table: performance / difference?

前端 未结 2 498
不思量自难忘°
不思量自难忘° 2020-12-29 07:02

I have created a sql function in SQLServer 2008 that declared a temporary table and uses it to compute a moving average on the values inside



        
相关标签:
2条回答
  • 2020-12-29 07:15

    The @table syntax creates a table variable (an actual table in tempdb) and materialises the results to it.

    The WITH syntax defines a Common Table Expression which is not materialised and is just an inline View.

    Most of the time you would be better off using the second option. You mention that this is inside a function. If this is a TVF then most of the time you want these to be inline rather than multi statement so they can be expanded out by the optimiser - this would instantly disallow the use of table variables.

    Sometimes however (say the underlying query is expensive and you want to avoid it being executed multiple times) you might determine that materializing the intermediate results improves performance in some specific cases. There is currently no way of forcing this for CTEs (without forcing a plan guide at least)

    In that eventuality you (in general) have 3 options. A @tablevariable, #localtemp table and a ##globaltemp table. However only the first of these is permitted for use inside a function.

    For further information regarding the differences between table variables and #temp tables see here.

    0 讨论(0)
  • 2020-12-29 07:20

    In addition to what Martin answered

    ;with tempTable as 
    (
        select * from aces.dbo.fEDVisitCounts('ALL', null,DATEADD(DD,-7,'01-09-2010'),
            '04-09-2010',0,130,null,1, 0)
    )
    
    SELECT * FROM tempTable
    

    can also be written like this

    SELECT * FROM 
    (
        select * from aces.dbo.fEDVisitCounts('ALL', null,DATEADD(DD,-7,'01-09-2010'),
            '04-09-2010',0,130,null,1, 0)
    ) AS tempTable  --now you can join here with other tables
    
    0 讨论(0)
提交回复
热议问题