I created a simple select for this and it workedSelect * from @post a where postid = 1 or parentpostid =1 or parentpostid in( select postid from @post where parentpostid =1)
but when I added more data with more levels it didn't, so I created a loop. The solution is very muchlike jeff's but with less variablesDeclare @post table( PostID int, ParentPostID int, Author nvarchar(5), Subject nvarchar(50))--Data with more levelsinsert into @postselect 1,null,'User1', 'Problem' unionselect 2, 1, 'User2', 'Re: Problem' unionselect 3, null, 'User3', 'Different Problem' unionselect 4, 1, 'User4', 'Re: Problem' unionselect 5, 2, 'User5', 'Re: Re: Problem' unionselect 6, 5, 'User5', 'Re: Re: Re: Problem' unionselect 7, 6, 'User5', 'Re: Re: Re: Problem' unionselect 8, 7, 'User5', 'Re: Re: Re: Re: Problem' unionselect 9, 8, 'User5', 'Re: Re: Re: Re: Re: Problem' unionselect 10, 9, 'User5', 'Re: Re: Re: Re: Re: Re: Problem' unionselect 11, 10, 'User5', 'Re: Re: Re: Re: Re: Re: Re: Problem' unionselect 12, 3, 'User6', 'Re: Different Problem' unionselect 13, 4, 'User1', 'Re: Problem - Fixed'
Solutiondeclare @postID intdeclare @results table( PostID int, ParentPostID int, Author nvarchar(5), Subject nvarchar(50))set @postID = 1insert into @resultsselect * from @post pWhere postID=@postID While @@rowcount>0begin insert into @results select * from @post p Where exists ( select 1 from @results r Where p.parentpostid = r.postid ) and not exists ( select 1 from @results r Where p.postid = r.postid )end
ResultsPostID ParentPostID Author Subject ----------- ------------ ------ -------------------------------------------------- 1 NULL User1 Problem2 1 User2 Re: Problem4 1 User4 Re: Problem5 2 User5 Re: Re: Problem13 4 User1 Re: Problem - Fixed6 5 User5 Re: Re: Re: Problem7 6 User5 Re: Re: Re: Problem8 7 User5 Re: Re: Re: Re: Problem9 8 User5 Re: Re: Re: Re: Re: Problem10 9 User5 Re: Re: Re: Re: Re: Re: Problem11 10 User5 Re: Re: Re: Re: Re: Re: Re: Problem
*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*A candle loses nothing by lighting another candle