if object_id('tempdb..#t') is not null drop table #t
create table #t(categoid int,categoname varchar(10),parentid int)
insert into #t
select 8,'2222',0
union all
select 9,'2345',8
union all
select 12,'we32',9
;
with cte
as (
select categoname,parentid,1 as lvl,cast(categoname as varchar(8000)) as paths
from #t
where categoid=12
union all
select a.categoname,a.parentid,b.lvl+1,a.categoname+'\'+b.paths
from #t a join cte b
on a.categoid=b.parentid
)
select * from cte where lvl=(select max(lvl) from cte)