sql server - Get Parent and grand parents of a particular child -


i have table below

tablename :exampletable

childid       childcommonid   parentid   1               2                0  2               3                0  3               4                1  4               5                3  5               6                4 

the problem :

i have child id example :childid= 5

so need check wheather has parent or not if contain parent check corresponsing parentid, in case parentid 4 need check child 4 has parent ,in case parentid of child 4 3, gain check child 3 has parent in case child 3 has parent 1, check child 1 has parents here child 1 top grand parent , has no parent stop process , return childids 1

here expected output

childid  5 4 3 1 

i had tried below not give correct output

with getallparent (    select *     exampletable     childid  = 5    union    select *    exampletable c       left join getallparent p on p.childid = c.parentid  )  select * getallparent; 

if need sample data can use below query

create table exampletable(childid int,childcommonid int ,parentid int ) insert exampletable values(1,2,0) insert exampletable values(2,3,0) insert exampletable values(3,4,1) insert exampletable values(4,5,3) insert exampletable values(5,6,4) 

any appreciated

like comment, columns incorrect in join. use getallparent p on p.parentid = c.childid.

with getallparent (    select childid,parentid    exampletable     childid  = 5    union    select c.childid,c.parentid    exampletable c       inner join getallparent p on p.parentid = c.childid  )  select * getallparent; 

fiddle


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

c# - Exception when attempting to modify Dictionary -