父表和子表之间的CTE递归

时间:2016-03-11 19:10:15

标签: sql-server database recursion

帮助!我有一个父表和一个子表。这些表用作使用sql server的物料清单结构的参考。这两个表包含所有BOM数据。

我想设置一个递归SQL查询,其中建立一个子项,然后查询以递归方式检查所有父项。出于某种原因,我的查询仅深入一级并停止。我一直无法确定原因。在阅读许多递归CTE示例时,它始终使用自引用表(即一个表),但在我的示例中,两个表之间的引用循环。

我添加了一个步骤列,作为已完成递归级别的指标。

以下是我的查询,但不起作用。

DECLARE @pn NVarchar(50);
SET @pn = 'fastener';

WITH CTE AS 
(
    SELECT      STEPS = 1,
                Item.IMA_ItemID AS CID,
                ProductStructure.PST_QtyPerAssy AS QPA, 
                Item_1.IMA_ItemID AS PID 
    FROM        dbo.Item Item 
    INNER JOIN  dbo.ProductStructure ProductStructure
    ON          Item.IMA_RecordID = ProductStructure.PST_IMA_RecordID -- This links the child table to the item table (to get it's p/n)
    INNER JOIN  dbo.ProductStructureHeader ProductStructureHeader -- This links the child table to parent table
    ON          ProductStructureHeader.PSH_RecordID = ProductStructure.PST_PSH_RecordID     
    INNER JOIN  dbo.Item Item_1 -- This links the parent table to the item table (to get it's p/n)
    ON          Item_1.IMA_RecordID = ProductStructureHeader.PSH_IMA_RecordID
    WHERE       Item.IMA_ItemID=@pn --Establishes seed p/n (fastener)
            AND Item_1.IMA_DefaultRev=1 --Only shows parent's which are default

    UNION   ALL

    SELECT      CTE.STEPS + 1, --Denotes recursion level +1
                xItem.IMA_ItemID AS CID,
                xProductStructure.PST_QtyPerAssy AS QPA, 
                xItem_1.IMA_ItemID AS PID 
    FROM        dbo.Item xItem 
    INNER JOIN  dbo.ProductStructure xProductStructure
    ON          xItem.IMA_RecordID = xProductStructure.PST_IMA_RecordID -- Links child to item table to get part number
    INNER JOIN  dbo.ProductStructureHeader xProductStructureHeader
    ON          xProductStructureHeader.PSH_RecordID = xProductStructure.PST_PSH_RecordID       -- Links child table to parent table
    INNER JOIN  dbo.Item xItem_1
    ON          xItem_1.IMA_RecordID = xProductStructureHeader.PSH_IMA_RecordID --Links parent table to item table to get part number

    INNER JOIN  CTE 
    ON          PID = CTE.CID --Links child search results to parent on previous search
)
SELECT * FROM CTE

0 个答案:

没有答案