0

我有下表

PNLTable([PnlId], 
          [Line], 
          [TotalisationId], 
          [Designation], 
          [Totalisation],
          ParentId).

我使用以下查询为每个 pnlid 获取所有孩子

;WITH CTE 
AS
(
    SELECT PNLId ,concat('/',cast(PNLId as nvarchar(MAX)) )as tree, PNLParentId
    FROM [dbo].[DimPNL]
    WHERE PNLParentId IS NULL 
    UNION ALL
    SELECT T1.PNLId,concat( CTE.tree ,'/',cast(t1.PNLId as nvarchar(MAX))), T1.PNLParentId
    FROM [dbo].[DimPNL] AS T1
    INNER JOIN CTE
    ON T1.PNLParentId = CTE.PNLId
)
SELECT *
FROM CTE

我使用了一个存储过程 spGetResult,它使用一些约束来更新 Totalisation。

我如何结合spGetResultstarting上面的查询,以便开始从最低的子级递归更新到高级(根)?

4

1 回答 1

0

您可以将排序的结果插入#temp表中,然后使用游标遍历结果,如下所示:

;WITH CTE 
AS
(
    SELECT PNLId ,concat('/',cast(PNLId as nvarchar(MAX)) )as tree, PNLParentId
    FROM [dbo].[DimPNL]
    WHERE PNLParentId IS NULL 
    UNION ALL
    SELECT T1.PNLId,concat( CTE.tree ,'/',cast(t1.PNLId as nvarchar(MAX))), T1.PNLParentId
    FROM [dbo].[DimPNL] AS T1
    INNER JOIN CTE
    ON T1.PNLParentId = CTE.PNLId
)
-- order the results into a #temp table
SELECT *
INTO #temp
FROM CTE
ORDER BY PNLId, PNLParentId DESC -- set this accordingly

DECLARE @pnlId int   
DECLARE @pnlParentId int   

DECLARE db_cursor CURSOR FOR  
SELECT PNLId, PNLParentId 
FROM #temp 

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @pnlId, @pnlParentId    

WHILE @@FETCH_STATUS = 0   
BEGIN   
       -- call ytour stored proc with required params here
       Exec [spGetResultstarting] @pnlId, @pnlParentId

       FETCH NEXT FROM db_cursor INTO @pnlId, @pnlParentId   
END   

CLOSE db_cursor   
DEALLOCATE db_cursor
于 2014-05-14T10:02:14.460 回答