I have a script that is meant to find the originalLocation.
It starts with a table like this:
+----+------------+----------+
| ID | PreviousID | Location |
+----+------------+----------+
| 2 | NULL | 1235 |
| 3 | 2 | 1236 |
| 4 | 3 | 1239 |
| 8 | 11 | 1237 |
| 9 | 8 | 1234 |
| 10 | 9 | 1235 |
| 11 | 10 | 1237 |
+----+------------+----------+
I want to find the original Location for a select number of ID values
+----+
| ID |
+----+
| 4 |
| 8 |
| 10 |
| 11 |
+----+
The result I am looking for is:
+-----+----+------------+----------+------------------+
| lvl | ID | OriginalId | Location | OriginalLocation |
+-----+----+------------+----------+------------------+
| 0 | 2 | 2 | 1235 | 1235 |
| 2 | 4 | 2 | 1239 | 1235 |
| 0 | 8 | 8 | 1237 | 1237 |
| 2 | 10 | 8 | 1235 | 1237 |
| 3 | 11 | 8 | 1237 | 1235 |
+-----+----+------------+----------+------------------+
The output for ID =2 and =4 is good.
However, with 8,10,11, this result in circular reference and the code break.
Question: Is there away to address this issue so that the error does not occur (“The statement terminated. The maximum recursion 100 has been exhausted before statement completion.”) and produce the desired outputs?
Here is the script that I have so far to produce output for ID 2 and 4. It works if you remove value 8,10,11
DECLARE @IDs TABLE (
ID INTEGER
,PreviousID INTEGER
,Location INTEGER
)
INSERT INTO @IDs
SELECT 2,null,1235
UNION ALL SELECT 3,2,1236
UNION ALL SELECT 4,3,1239
UNION ALL SELECT 8,11,1237
UNION ALL SELECT 9,8,1234
UNION ALL SELECT 10,9,1235
UNION ALL SELECT 11,10,1237
Select * from @IDs
DECLARE @ORDERID Table (OrderID nvarchar (100))
Insert into @ORDERID values
('2')
,('4')
--,('8')
--,('10')
--,('11')
;WITH q AS (
SELECT 0 lvl, ID, PreviousID,PreviousID LastId
,Location,Location as OriginalLocation
FROM @IDs
where ID in (select OrderID from @ORDERID)
UNION ALL
SELECT lvl+1, q.ID,u.PreviousId,q.PreviousId LastId
,q.Location,u.Location
FROM q
INNER JOIN @IDs u ON u.ID = q.PreviousID
--and q.ID <> u.PreviousID and q.PreviousID <> u.ID
)
select lvl, ID, coalesce(LastId,Id) OriginalId,Location,OriginalLocation
from q
where PreviousId is null
order by id;
Thank you very much for your any hint or suggestion.