Nog een kortere CTE:
WITH cte AS(
SELECT *, id AS topparent
FROM t
WHERE parentid IS NULL
UNION ALL
SELECT t.*, c.topparent
FROM t JOIN cte c ON c.id = t.parentid
WHERE t.id <> t.parentid
)
SELECT * FROM cte
Hier getest:SQL Fiddle
BEWERKEN :Deze verdomde SQLfiddle reageert weer niet. Test de DDL-code hieronder
CREATE table t (id INT, parentid INT);
INSERT INTO T VALUES (1 , NULL );
INSERT INTO T VALUES (2 , 1 );
INSERT INTO T VALUES (3 , 2 );
INSERT INTO T VALUES (9 , NULL );
INSERT INTO T VALUES (5 , 9 );
INSERT INTO T VALUES (6 , 5 );
INSERT INTO T VALUES (25 , NULL );
INSERT INTO T VALUES (30 , 25 );