--dirid:栏目ID name:栏目名称 pdirid:上级栏目ID
set nocount on
create table tb(dirid int,dirname varchar(20),pdirid int)            
insert tb
select 1,'中学',0 union all
select 2,'成考',0 union all
select 3,'注会',0 union all
select 4,'计算机',0 union all
select 5,'考研',0 union all
select 6,'司考',0 union all
select 7,'公务员',0 union all
select 8,'MBA',0 union all
select 9,'外语',0 union all
select 10,'高中',1 union all
select 11,'初中',1 union all
select 12,'高一',10 union all
select 13,'高二',10 union all
select 14,'高三',10 union all
select 15,'初一',11 union all
select 16,'初二',11 union all
select 17,'初三',11
--类似上边的数据库结构,想把某一栏目下而所有包含的栏目都查出来(不知道有几层),有没有什么好的方法?
go
create function f_str(@dirid int)
returns varchar(8000)
as
begin
declare @i int,@re varchar(8000)
declare @tb table (id int ,dirid int,dirname varchar(20),pdirid int)
set @re=''
set @i=1
insert into @tb
select @i,dirid,dirname,pdirid from tb where dirid=@dirid
while  @@rowcount>0
begin
set @i=@i+1
insert into @tb
select @i,b.dirid,b.dirname,b.pdirid
from @tb a,tb b where a.dirid=b.pdirid and a.id=@i-1
endselect @re=@re+'\'+dirname from @tb order by id
return stuff(@re,1,1,'')
end
go
select dirid,dbo.f_str(dirid) from tbdrop table tb
drop function dbo.f_str