I have table with such structure.
ElementId | ParentId
-------------------
1 | NULL
2 | 1
3 | 2
4 | 3
Let 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 | 3
Let 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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AartiPosted Dec 10, 2013, 1:37 AM
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 ;
Bhupendra SinghPosted Jun 10, 2013, 5:44 AM
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
Pankaj PandeyPosted Jun 10, 2013, 5:15 AM
could you explain a little more , i am not able to get your question
please write all condition and table properly.