我有下面的 SQL CTE 语句,我发现它是性能的瓶颈。在调试时,它只是挂在那里(我认为它会进行表扫描)所以我用一个临时表替换它并且查询运行良好。我想知道 CTE 表达式的编写方式是否存在使语句挂起的差异。我知道 CTE 附带了一些性能影响,但我认为我在下面的查询中没有做任何特别的事情来使 CTE 给我如此糟糕的性能。
;with ContList (ContKey, CKey, CreatedDate, DeletedDate, SourceId) AS
(
SELECT ContKey, CKey, CreatedDate, DeletedDate, SourceId FROM #someTempTable
UNION ALL
SELECT list.ContKey AS ContKey,
fact.CKey AS CKey,
case when fact.CreatedDate > list.CreatedDate then fact.CreatedDate else list.CreatedDate end AS CreatedDate,
case when isnull(fact.DeletedDate, '9999/01/01') < isnull(list.DeletedDate, '9999/01/01') then fact.DeletedDate else list.DeletedDate end AS DeletedDate,
fact.DataSourceDimKey As SourceId
FROM ContList list
INNER JOIN SomeFact fact ON list.CKey = fact.DimKey
INNER JOIN SomeDimvw someDim on someDim.SomeKey = fact.SomeKey
INNER JOIN #contTypes contTypes on someDim.SomeTypeId = contTypes.SomeTypeId
WHERE list.DeletedDate IS NULL
)
我用这个替换了上面的查询:
SELECT ContKey, CKey, CreatedDate, DeletedDate, SourceId FROM #someTempTable
UNION ALL
SELECT list.ContKey AS ContKey,
fact.CKey AS CKey,
case when fact.CreatedDate > list.CreatedDate then fact.CreatedDate else list.CreatedDate end AS CreatedDate,
case when isnull(fact.DeletedDate, '9999/01/01') < isnull(list.DeletedDate, '9999/01/01') then fact.DeletedDate else list.DeletedDate end AS DeletedDate,
fact.DataSourceDimKey As SourceId
into #ContList
FROM #ContList list
INNER JOIN SomeFact fact ON list.CKey = fact.DimKey
INNER JOIN SomeDimvw someDim on someDim.SomeKey = fact.SomeKey
INNER JOIN #contTypes contTypes on someDim.SomeTypeId = contTypes.SomeTypeId
WHERE list.DeletedDate IS NULL
)