sql - recursive cte - mark all leafs -


i have recursive cte that's working fine, need 1 more thing: add [isleaf] flag each result, tell if record has more children ([leafs] field children counter better).

working example pasted below. counts level of every category , joins names category path, sql server doesn't allow left join, top, select distinct, aggregates , subqueries used in recursive part of cte, obvious methods of doing need.

drop table cats go create table cats(     catid int primary key clustered,     parent int, --parent's catid. 0 top-level entries     name    varchar(255) ) go  insert cats (catid, parent, name) select 1 catid, 0 parent, 'computers' name union      select 2, 1, 'laptops' union          select 4, 2, 'ibm' union          select 5, 2, 'others' union      select 3, 1, 'desktops' union          select 6, 3, 'amd' union          select 7, 3, 'others' union  select  8, 0 , 'cars' union      select 9, 8, 'others' union      select 10, 8, 'pickups' union          select 11, 10, 'others' union          select 12, 10, 'ford' union              select 14, 12, 'ranger' union              select 15, 12, 'others' go        ;with ctecat (     select          catid, parent,         [ctelevel]  = 1,         [ctepath]   = cast(name varchar(4000))         --,[cteisleaf]  = 0     cats     1=1         , parent=0 union      select          c.catid, c.parent,         [ctelevel] = cc.ctelevel+1,         [ctepath] = cast(cc.ctepath + ' | ' + c.name varchar(4000))         --,[cteisleaf]  = 0 --???--     cats c     join ctecat cc         on c.parent = cc.catid     1=1         , c.parent<>0 ) select      *  ctecat order      catid 

easiest thing implement add corraleted subquery in final select statement checks isleaf. it's simple check see if particular catid someone's parent or not. not require recursion.

select     * ,  case when exists (select * cats c2 c2.parent = c1.catid) 0 else 1 end isleaf ctecat c1 order     catid 

edit: if need [leafs] count of imminent children it's simple them:

select     *      , case when exists (select * cats c2 c2.parent = c1.catid) 0 else 1 end isleaf     , (select count(*) cats c2 c2.parent = c1.catid) leafs ctecat c1 order      c1.catid 

sqlfiddle demo

but, if need [leafs] total counter of children , of chieldren's children require rewriting cte (to go bottom-up instead of top-to-bottom).


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -