Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
hello friends i have a table like this.

ID Parent
1 Null
2 1
3 2
4 Null
5 1
6 4

Now i want to count all children for a parent id in this table up to n level. like ID 1 have 3 children, 4 has 1 child , 2 has one and so on. Please help me , how can i achieve that .
thanks in advance friends.
Posted

try this...

create function [dbo].[myfunction]
(
@p_P int
)
returns int
begin
declare @output int
select @output=count(*) from P_table where parent=@p_P
return @output
end
go
select distinct parent, dbo.myfunction(parent) as 'No of child(ren)' from p_table
 
Share this answer
 
Firstly, have a look at the output of this query :
SQL
declare @nodeid int
set @nodeid = 109;

with rootCTE(id, parentid, level )
as
(
select id, parent ,1
from table
    where parent = @nodeid

union all
select e.id, e.parent , r.level+1 from table t, rootCTE r where t.parent = r.id
)
select * from rootCTE


Then to get the count of children up to level 2 run this one :

SQL
declare @nodeid int
set @nodeid = 109;

with rootCTE(id, parentid, level )
as
(
select id, parent ,1
from table
    where parent = @nodeid

union all
select e.id, e.parent , r.level+1 from table t, rootCTE r where t.parent = r.id
)
select COUNT(*)  from rootCTE
where level<=2


To count all children remove the where clause.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900