I have table with such structure.
SQL
ElementId | ParentId
-------------------
1 | NULL
2 | 1
3 | 2
4 | 3Let say current element has Id 4. I want to select all parent ids. Result should be: 3, 2, 1
I have table with such structure.
ElementId | ParentId
-------------------
1 | NULL
2 | 1
3 | 2
4 | 3Let say current element has Id 4. I want to select all parent ids. Result should be: 3, 2, 1
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Pankaj PandeyRank #642 · 3.7K reputationPosted Jun 10, 2013, 1:15 AM EDT
could you explain a little more , i am not able to get your question
please write all condition and table properly.
Bhupendra SinghRank #4,382 · 347 reputationPosted Jun 10, 2013, 1:44 AM EDT
parent id is its own table id, means its identity column
i have a id 9 ,i want to select all parent ids hierarchy
and result is according to id 9 should be:6,3,1
and also id 8 result should be:5,2,1
----------------------------
id parent_id rank
----------------------------
1 null 50
2 1 52
3 1 52
4 2 53
5 2 52
6 3 52
7 4 51
8 5 51
9 6 51
I want to search all parent hierarchy
AartiRank #2,383 · 594 reputationPosted Dec 9, 2013, 8:37 PM EST
Hi Bhupendra,
TRY WITH BELOW FUNCTION TO GET ALL PARENTIDS.
create function [dbo].[fGetallParentids](@ElementId int)
returns @t table (
ParentID int
)
as
begin
declare @newElementId int
insert into @t
select ParentID from tablename
where ElementId = @ElementId
select @ElementId=iDocParentID from tablename
where ElementId = @ElementId
declare cur CURSOR LOCAL for
select ParentID from @t where ParentID = @ElementId
open cur
fetch next from cur into @newElementId
while @@FETCH_STATUS = 0
BEGIN
insert into @t
select ParentID from fGetallParentids( @newElementId)
fetch next from cur into @newElementId
END
close cur
deallocate cur
return
end
-----------
-- select * from fGetallParentids(4)
Result will be: 3,2,1 ;