Если вы хотите рассчитывать для категории 3
create table #temp
(
id int,
parent_id int,
code int,
name varchar(20)
)
insert into #temp values(1,null,0,'category 1')
insert into #temp values(2,null,1,'category 2')
insert into #temp values(3,null,2,'category 3')
insert into #temp values(4,null,3,'category 4')
insert into #temp values(5,3,4,'category 5')
insert into #temp values(6,null,5,'category 6')
insert into #temp values(7,5,0,'category 7')
insert into #temp values(8,null,1,'category 8')
insert into #temp values(9,7,2,'category 9')
insert into #temp values(10,null,3,'category 10')
insert into #temp values(11,null,4,'category 11')
insert into #temp values(12,null,5,'category 12')
;WITH items AS (
SELECT id,name,parent_id
FROM #temp
WHERE parent_id is null and id=3
UNION ALL
SELECT i.id,i.name,i.parent_id
FROM #temp i
INNER JOIN items itms ON itms.id = i.parent_id
)
SELECT count(*) FROM items