We have a loop in SQL Server 2005 that loops around on a table getting each items parent until it gets to the top of the tree:
DECLARE @T Table
(
ItemID INT NOT NULL PRIMARY KEY,
AncestorID INT NULL
)
Which has data like this:
ItemID | AncestorID
1 2
2 3
3 4
4 NULL
We have a loop that basically does this:
DECLARE @AncestorID INT
SELECT @AncestorID = 1
WHILE (@AncestorID IS NOT NULL)
BEGIN
--Do some work
SELECT @AncestorID = T.AncestorID
FROM @T t
WHERE T.ItemID = @AncestorID
print @AncestorID
END
(Yes I know SQL is set based, and this is processing row by row, the “Do some work” needs to be done line by line for a reason).
This has always worked fine until today when we ended up in an endless loop. Turns out the cause was some wrong data:
ItemID | AncestorID
1 2
2 3
4 NULL
ItemID 3 was deleted. The loop now never ends because AncestorID is never NULL – it stays at 3.
Is there anyway to rewrite the select statement to make @AncestorID null if the SELECT query returns 0 rows, or do I need to have a separate SELECT statement to count the records and some IF ELSE type logic?
You can use an aggregate on
T.AncestorID.