Thursday 6 August 2009

SQL: A recursive query for a self-reference table

I was working with a self-reference table and wanted to query the parent-child relationship.



Say, given an ExceptionRepositoryId, I want to display all its children. After a little while I came up with a recursive SQL:
DECLARE @parentId int
SET @parentId = 210;

WITH TEMP (ExceptionRepositoryId, ParentExceptionRepositoryId)
AS
(
SELECT
ExceptionRepositoryId, ParentExceptionRepositoryId
FROM
dbo.tbl_ExceptionRepository
WHERE
ExceptionRepositoryId = @parentId
UNION ALL
SELECT
t1.ExceptionRepositoryId, t1.ParentExceptionRepositoryId
FROM
dbo.tbl_ExceptionRepository t1
inner join TEMP t2 ON t1.ParentExceptionRepositoryId = t2.ExceptionRepositoryId
)
SELECT * FROM TEMP
And I am happy to get the results like the following: