SELECT
tchart.*
INTO
#OrderSections
FROM
Order.Charts tchart
INNER JOIN
(
SELECT
tchart.ID,
tchart.ORCode,
tchart.SectionalDistance,
row_number() OVER( PARTITION BY rrs.ORCode ORDER BY tchart.VendorTimestampUTC DESC, tchart.InsertedTimestampUTC DESC, tchart.ID DESC ) AS RecordIndex
FROM
#OrderStaging rrs
INNER JOIN
Order.Charts tchart
ON
rrs.ORCode = tchart.ORCode
) AS Latest_tchart
ON
tchart.ID = Latest_tchart.ID
WHERE
Latest_tchart.RecordIndex = 1;
With cte as(
SELECT
tchart.ID,
tchart.ORCode,
tchart.SectionalDistance,
row_number() OVER( PARTITION BY rrs.ORCode ORDER BY tchart.VendorTimestampUTC DESC, tchart.InsertedTimestampUTC DESC, tchart.ID DESC ) AS RecordIndex
FROM
#OrderStaging rrs
INNER JOIN
Order.Charts tchart
ON
rrs.ORCode = tchart.ORCode)
SELECT
cte.*
INTO
#OrderSections
FROM
cte
WHERE
RecordIndex = 1
CTE会对存储过程产生很大影响吗?
答案 0 :(得分:1)
要回答有关效果和执行计划的问题,您应该查看查询的特定计划。
但是,无论逻辑是在子查询还是CTE中,我都希望查询具有相同的执行计划。这在SQL Server中是正确的,但不适用于其他数据库。例如,Postgres实现了CTE,因此您会期望性能差异。
编辑:
分层查询(递归CTE)需要CTE。对于其他查询,它们是方便的 - 并且可以非常方便,因为您可以在同一查询中多次引用CTE。但是,它们对SQL Server中的执行计划没有特定的影响。 CTE被替换为查询,整个处理被优化为一次。