微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

CTE被多次呼叫了?

如何解决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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。