एक पुनरावर्ती 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