表结构这样:key,parentKey,name,然后创建一个函数可自动生成一个临时表,该临时表包含
key,parentKey,name,还有path.其中path为name1/name2/name3/这样的结构。
要查询所有name1的子,只要select * from Argu() where name like 'name1%'
--邹建 2003.9--*/
create table tb(id int identity(1,1) not null constraint PK_tb primary key clustered
,pid int,name varchar(20))
insert into tb
select 0,'中国'
union all select 0,'美国'
union all select 0,'加拿大'
union all select 1,'北京'
union all select 1,'上海'
union all select 1,'江苏'
union all select 6,'苏州'
union all select 7,'常熟'
union all select 6,'南京'
union all select 6,'无锡'
union all select 2,'纽约'
union all select 2,'旧金山'
go
--查询指定id的所有子的函数
create function f_cid(
@id int
)returns @re table(userid int,[level] int)
as
begin
declare @l int
set @l=0
insert @re select @id,@l
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.userid,@l
from Nuser a,@re b
where a.mangername=b.userid and b.[level]=@l-1
end
return
end
go
--调用(查询所有的子)
select a.*,层次=b.[level] from Nuser a,f_cid(2)b --查询 userid=2 的所有下级
where a.userid=b.userid