SQL recursive CTE query, odd results set SQL Server 2005 -


i trying write recursive cte query in sql server 2005 getting odd set of results. table is:

pairid  childid parentid 900        1        2        901        2        3        902        3        4        

this cte query:

with tester (pairid,               childid,               parentid,               level) (select a.pairid, a.childid,a.parentid, 0 level     businesshierarchy     union     select b.pairid, b.childid, b.parentid, oh.level + 1 level     businesshierarchy b inner join     tester oh on b.childid =  oh.parentid) select        x.pairid,        x.childid,       x.parentid,       x.level  tester x  order x.level, x.childid, x.parentid 

ok, getting dataset return, however, not expected in contains repetition in following manner:

pairid  childid parentid level 900     1       2        0 901     2       3        0 902     3       4        0 ...  900     2       3        1 901     3       4        1 ...  900     3       4        2 

if explain me why happening , how correct grateful.

as far last question goes, how have modify display initial childid each of parents this:

original pairid  childid parentid level 900     1       2        0 901     2       3        1 902     3       4        2  want displayed as: pairid  childid parentid level 900     1       2        0 901     1       3        1 902     1       4        2 

your problem starting point. first part of cte query returns rows (notice level 0).

then - next part of query go , related rows (which adds earlier resultset).

i did notice, however, have no record id of 4

if did, here do:

;with tester (pairid, childid, parentid, level) (     select         a.pairid,         a.childid,         a.parentid,         0 level     businesshierarchy     left join businesshierarchy a2 on a.parentid = a2.childid     a2.pairid null      union      select         b.pairid,         b.childid,         b.parentid,         oh.level + 1 level     businesshierarchy b     inner join tester oh on b.parentid =  oh.childid )  select      x.pairid,      x.childid,     x.parentid,     x.level tester x order x.level, x.childid, x.parentid 

also, see my answer similar question show correct sort order (using path)


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -