CTE被多次呼叫了?

问题描述

我的任务是调查一个非常慢的SQL查询。如果我对CTE的理解是正确的,则每次在外部查询调用CTE时都会调用它们。

WITH 

UserAccount 
    AS
        (
            SELECT uaa.AccountId FROM Paymentinitiation.UserAccountAccess uaa
            WHERE uaa.UserId = @userId
        ),CTE_TransactionId (TransactionId)
    AS
        (
            SELECT TOP 100 TransactionId 
            FROM   Paymentinitiation.TransactionMetaDataDebit T 
            JOIN   UserAccount UA ON T.AccountId = UA.AccountId  
            WHERE   T.TransactionId < @seekPoint ORDER BY T.TransactionId DESC
        ) 
        
SELECT 
    PT.Id,InstructionId,ContractReference,CpgReference,ModuleTypeId,ProductType,PT.ModifiedAt,VirtualAccountId,CounterpartyExchangeRate 
FROM Paymentinitiation.PaymentTransactions PT 
JOIN CTE_TransactionId P ON PT.Id = P.TransactionId

查询将导致执行计划带有嵌套循环和大量执行。

enter image description here

enter image description here

所以我的问题确实是-CTE是否由于在集合中的earch行上执行而导致查询阻塞?

还是我看错了?

非常感谢。

解决方法

我认为您希望得到这样的结果

with CTE_TransactionId (TransactionId) AS (
    SELECT TOP 100 TransactionId 
    FROM   PaymentInitiation.UserAccountAccess uaa 
            join PaymentInitiation.TransactionMetaDataDebit T on uaa.AccountId=T.AccountId
    WHERE  UAA.UserId=@userId 
            and T.TransactionId < @seekPoint 
    ORDER BY T.TransactionId DESC) 
SELECT 
    PT.Id,InstructionId,ContractReference,CpgReference,ModuleTypeId,ProductType,PT.ModifiedAt,VirtualAccountId,CounterpartyExchangeRate 
FROM PaymentInitiation.PaymentTransactions PT 
     join CTE_TransactionId P ON PT.Id = P.TransactionId;