sql server - SQL query for parent-child chain -


i have single table can refer 1 other member in table parent. parent refer 1 other row parent...and on.

id     col1     col2    parentid 1      foo      bar       null 2      blah     boo       1 3      fob      far       2 4      wob      lob       null 

i return chain given id. if id 3 return row 3, row 2 , row 1. if id 2 return row 2 , row 1. if id 1 or 4 return row.

thank you

use recursive cte:

declare @id int     set @id = 3  ;with hierarchy (   select t.id, t.parentid     your_table t    t.id = @id  union  select x.id, x.parentid    your_table x    join hierarchy h on h.parentid = x.id) select h.id   hierarchy h 

results:

id --- 3 2 1 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -