光标中的CTE给出“连接忙于另一个命令的结果”错误,而派生表则没有

时间:2014-01-20 20:45:32

标签: sql sql-server tsql common-table-expression derived-table

我最近在从使用CTE的查询的光标中获取时遇到了错误。

“[Microsoft] [SQL Server本机客户端10.0]连接失败,其他命令的结果为”

在fetch的每次迭代中执行的后续游标上发生错误。

我能够通过用派生表替换CTE来解决错误。

我需要知道为什么派生表工作正常,而CTE失败,如果我在CTE示例中做错了。

原始查询相对复杂,涉及多个连接,但基本上相当于以下内容:

WITH cteResults AS (
    SELECT Account.Id AS AccountId
    FROM Accounts AS Account
    WHERE Account.Number = '12345'
    UNION
    SELECT SubAccount.Id
    FROM SubAccounts AS SubAccount
    WHERE SubAccount.Number = '12345')

SELECT
    Invoice.Value AS InvoiceValue,
    CASE
        WHEN Representative.Sequence IS NOT NULL THEN THEN Representative.Name
        ELSE Account.OwnerName
    END AS InvoiceName
FROM cteResults
INNER JOIN Invoices AS Invoice ON
    Invoice.AccountId = cteResults.AccountId
LEFT OUTER JOIN Accounts AS Account ON
    Account.Id = Invoice.AccountId
LEFT OUTER JOIN AccountRepresentatives AS Representative ON
    Representative.Id = Invoices.AccountRepresentativeId

有问题的代码将使用上面的语句遍历游标,并且对于FETCH的每次迭代,它将执行第二个游标:

FOREACH InvoicesCursor INTO InvoiceResults.*
    OPEN FormattingRulesCursor
    FETCH FormattingRulesCursor into FormattingRules.*
    // Error appears here
    CLOSE FormattingRulesCursor
END FOREACH

在FOREACH语句期间从应用程序打开的任何游标都会因上面提到的错误而失败。

但是,如果我删除CTE并使用派生表,我就不会收到错误,一切正常。

SELECT
    Invoice.Value AS InvoiceValue,
    CASE
        WHEN Representative.Sequence IS NOT NULL THEN THEN Representative.Name
        ELSE Account.OwnerName
    END AS InvoiceName
FROM (SELECT Account.Id AS AccountId
    FROM Accounts AS Account
    WHERE Account.Number = '12345'
    UNION
    SELECT SubAccount.Id
    FROM SubAccounts AS SubAccount
    WHERE SubAccount.Number = '12345') AS cteResults
INNER JOIN Invoices AS Invoice ON
    Invoice.AccountId = cteResults.AccountId
LEFT OUTER JOIN Accounts AS Account ON
    Account.Id = Invoice.AccountId
LEFT OUTER JOIN AccountRepresentatives AS Representative ON
    Representative.Id = Invoices.AccountRepresentativeId

0 个答案:

没有答案