CTE未被认可

时间:2014-09-19 00:13:12

标签: tsql

为什么我的CTE不能从我最后的选择中获取?我具体问我如何列出我的CTE,我遗漏了一些简单的事情,例如我如何分离最后两个

    with ParentsIdsWhoHaveInventoryWithManifests_CTE(brokerIds)
    as (...)
        ...)
        select someField from ParentsIdsWhoHaveInventoryWithManifests_CTE

    ;with SpecificBrokersTicketIds_CTE(ticketIds)
    as (...)
        select someFieldfrom ParentsIdsWhoHaveInventoryWithManifests_CTE

    ;with ProductionIdsWhichHaveManifests_CTE(productionIds)
    as (...)
        select productionIds from ProductionIdsWhichHaveManifests_CTE

    ;with InventoryRow_CTE(row)
    as (select row from Inventory where TicketId = @TicketId)

    ;with InvenotrySection_CTE(section)
    as (select section from Inventory where TicketId = @TicketId)


    select @ManifestId = ManifestId from Productions p where p.ProductionId = @ProductionId
    select @ProductionId as ProductionId_Used
    select @ManifestId as ManifestId_Used
    select @TicketId = TicketId from inventory where ProductionId = @ProductionId

...

update Venue_ManifestDetails
        set Row = row from InventoryRow_CTE,
        Section = section from InvenotrySection_CTE
        where TicketId = @TicketId

问题是我的更新声明中无法识别InventoryRow_CTEInvenotrySection_CTE CTE。

2 个答案:

答案 0 :(得分:2)

您只能在一个后续语句中使用CTE。您不能在2个或更多语句中使用它。

MSDN以这种方式解释:

  

公用表表达式(CTE)可以被认为是在单个 SELECT,INSERT,UPDATE,DELETE或CREATE VIEW语句的执行范围内定义的临时结果集。 / p>

如果要存储CTE的结果,请使用临时表或视图,并将CTE中的所有记录放入其中..

答案 1 :(得分:0)

CTE只是语法
如果你需要重复使用它重复它 我知道这看起来很奇怪但是就是这样 它只是语法 - 复制粘贴

您可以使用#temp或表变量