In one table I have two columns like below
ID ParentID
1 0x0
2 1
3 2
9 0x0
5 9
6 5
25 0x0
30 25
How to get top level parent ID
You can use a recursive CTE:
WITH CTE AS
(
SELECT *, 1 [Level]
FROM dbo.YourTable
UNION ALL
SELECT A.ID, B.[Parent ID], [Level] + 1
FROM CTE A
INNER JOIN dbo.YourTable B
ON A.[Parent ID] = B.Id
), CTE2 AS
(
SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY [Level] DESC)
FROM CTE
WHERE [Parent ID] <> 0
)
SELECT ID, [Parent ID] [Top Level Parent Id]
FROM CTE2
WHERE RN = 1
OPTION (MAXRECURSION 0)
;
Here is a link with a demo.
The results are:
╔════╦═════════════════════╗
║ ID ║ Top Level Parent Id ║
╠════╬═════════════════════╣
║ 2 ║ 1 ║
║ 3 ║ 1 ║
║ 5 ║ 9 ║
║ 6 ║ 9 ║
║ 30 ║ 25 ║
╚════╩═════════════════════╝