再帰CTE を使用します :
DECLARE @id INT
SET @id = 3
;WITH hierarchy AS (
SELECT t.id, t.parentid
FROM YOUR_TABLE t
WHERE t.id = @id
UNION ALL
SELECT x.id, x.parentid
FROM YOUR_TABLE x
JOIN hierarchy h ON h.parentid = x.id)
SELECT h.id
FROM hierarchy h
結果:
id
---
3
2
1