Domanda

I have the following table

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

I use the following query to get for each pnlid all children

;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

I used a stored procedure spGetResult which updates Totalisation with some constraints .

How can I combine between spGetResultstarting and the query above in order to start updating recursively from the lowest children to the high level (roots)?

È stato utile?

Soluzione

You can just insert your ordered results into a #temp table and use a cursor to iterate over the results something like this:

;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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top