如果CTE溢出到tempDB,临时表会是更好的选择吗?

时间:2018-10-10 10:22:50

标签: sql-server tsql

我有一个使用CTE定义员工部门的查询。

当查询优化器选择哈希匹配联接时,CTE溢出到tempdb。

  • 在这种情况下,使用临时表而不是CTE是更好的做法吗?
  • SQL尝试处理内存中的CTE是否有任何成本,但是必须使用可以通过有意将其定向为使用tempdb来减轻的tempdb?

如果有帮助,我的代码如下:

;WITH cte_Staff_Departments
AS (
    SELECT DISTINCT
        [stf].[contact_id]
        , CASE
            WHEN [stf].[department] NOT IN('HR', 'SALES', 'IT')
                THEN [dpt].[department]
                ELSE [stf].[department]
            END AS [Department]
    FROM [dbo].[staff] AS [stf]
        LEFT OUTER JOIN [dbo].[departments] AS [dpt] ON [stf].[contact_id] = [dpt].[contact_id]
    WHERE ([stf].[ownership_group] in ('COR','SLE')
        OR [dpt].[ownership_group] in ('COR','SLE')
) 
select contact_id, department from cte_Staff_Departments

谢谢 LS23

1 个答案:

答案 0 :(得分:0)

@ lindsayScott23,我只是建议。请不要把我打倒。我实际上将取消CTE,并使用子查询编写查询。像这样:

SELECT contact_id, department 
FROM (
    SELECT 
        [stf].[contact_id], 
        CASE
            WHEN [stf].[department] NOT IN('HR', 'SALES', 'IT')
                THEN [dpt].[department]
                ELSE [stf].[department]
        END AS [Department]
    FROM [dbo].[staff] AS [stf]
        LEFT JOIN [dbo].[departments] AS [dpt] 
            ON [stf].[contact_id] = [dpt].[contact_id]
            AND (
                [stf].[ownership_group] in ('COR','SLE')
                OR 
                [dpt].[ownership_group] in ('COR','SLE')
            )
) CSD
GROUP BY
    contact_id, department