鉴于下面的字段,我正在尝试循环到整个迭代集的第一次迭代。
+-------------------+----------------------+------------------------+
| id | nextiterationId | iterationCount |
+-------------------+----------------------+------------------------+
| 110001 | 110002 | 0 |
| 110002 | 110003 | 1 |
| 110003 | 110004 | 2 |
| 110004 | 1 | 3 |
因此,如果我使用 id
字段的值之一调用 SP/函数,我需要它返回给定的 id 的先前迭代,直到 iterationCount = 0
.
因此,如果我使用 id of 110003
(将其作为参数发送),它应该查询的第一件事是nextIterationID
为 110003
的 id
字段。这将是第一个循环。
由于迭代计数还不是 0,它会继续循环。然后它会根据第一个循环确定查找nextIterationID
110002
的 id,因此第二个循环将找到 110001
的"id"并返回它。由于该记录迭代计数 = 0,它将停止循环。
如果我使用 110003
调用 SP/函数,这是第 3 次迭代,它不会返回第 4 次迭代110004
,也没关系。我只需要它返回给定 id。
不久前,我以某种方式使用 WITH 和 WHILE 来做到这一点,但我现在不记得该怎么做。我需要以某种方式返回的格式,以便我可以在更大的 SELECT 语句中使用它。
这是一个递归的 cte 解决方案。让我知道它是否需要任何调整。
--Throwing your table into a temp table
CREATE TABLE #yourTable (ID INT,NextIterationID INT,IterationCount INT)
INSERT INTO #yourTable
VALUES
(110001,110002,0),
(110002,110003,1),
(110003,110004,2),
(110004,1,3)
--Now for the actual work
--Here is your parameter
DECLARE @param INT = 110003;
--Recursive CTE
WITH yourCTE
AS
(
--Initial Row
SELECT ID,
NextIterationID,
IterationCount
FROM #yourTable
WHERE NextIterationID = @param
UNION ALL
--Finding all previous iterations
SELECT #yourTable.*
FROM #yourTable
INNER JOIN yourCTE
ON yourcte.ID = #yourTable.NextIterationID
--Where clause is not really necessary because once there are no more previous iterations, it will automatically stop
--WHERE yourCTE.IterationCount >= 0
)
SELECT *
FROM yourCTE
--Cleanup
DROP TABLE #yourTable
结果:
ID NextIterationID IterationCount
----------- --------------- --------------
110002 110003 1
110001 110002 0