If there is a maximum depth you could use this approach. You can add further depth levels with simple copy and past and adapt. I added one data element "19,6" to generate one with three ancestors and one with four.
Just paste this into an empty query window and execute. Adapt to your needs...
declare @Test table (Id int, ParentID int)
insert into @Test values
(1,99)
,(2,9)
,(3,1)
,(4,2)
,(5,4)
,(6,3)
,(19,6);
WITH Ancestors1 AS
(
SELECT Test.*
,Ancestor.ParentID AS Anc1ID
FROM @Test AS Test
LEFT JOIN @Test AS Ancestor ON Test.ParentID=Ancestor.Id
)
,Ancestors2 AS
(
SELECT Ancestors1.*
, Ancestor.ParentID AS Anc2ID
FROM Ancestors1
LEFT JOIN @Test AS Ancestor ON Ancestors1.Anc1ID=Ancestor.Id
)
,Ancestors3 AS
(
SELECT Ancestors2.*
, Ancestor.ParentID AS Anc3ID
FROM Ancestors2
LEFT JOIN @Test AS Ancestor ON Ancestors2.Anc2ID=Ancestor.Id
)
SELECT Id,*
,COALESCE(Anc3ID,Anc2ID,Anc1ID,ParentID) AS LastAncId
FROM Ancestors3