sql - How to select parent ids -


i have table such structure.

elementid |  parentid ------------------- 1         | null 2         | 1 3         | 2 4         | 3 

let current element has id 4. want select parent ids. result should be: 3, 2, 1

how can it? db mssql

you can use recursive queries this: http://msdn.microsoft.com/en-us/library/aa175801(sql.80).aspx

you can use this:

with hierachy(elementid, parentid, level) (     select elementid, parentid, 0 level     table t     t.elementid = x -- insert parameter here     union     select t.elementid, t.parentid, th.level + 1     table t     inner join hierachy th     on t.parentid = th.elementid ) select elementid, parentid hierachy level > 0 

Comments

Popular posts from this blog

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

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

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