--树形数据查询示例
--作者: 邹建if exists (select * from dbo.sysobjects where id = object_id(N'[tb]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [tb]
GO--示例数据
create table [tb]([id] int identity(1,1),[pid] int,name varchar(20))
insert [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,'旧金山'
goif exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_id]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_id]
GO/*--树形数据处理 级别及排序字段--邹建 2003-12(引用请保留此信息)--*//*--调用示例 --调用函数实现分级显示
select replicate('-',b.[level]*4)+a.name
from [tb] a,f_id()b
where a.[id]=b.[id]
order by b.sid
--*/
create function f_id()
returns @re table([id] int,[level] int,sid varchar(8000))
as
begin
declare @l int
set @l=0
insert @re select [id],@l,right(10000+[id],4)
from [tb] where [pid]=0
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.[id],@l,b.sid+right(10000+a.[id],4)
from [tb] a,@re b
where a.[pid]=b.[id] and b.[level]=@l-1
end
return
end
go--调用函数实现分级显示
select replicate('-',b.[level]*4)+a.name
from [tb] a,f_id()b
where a.[id]=b.[id]
order by b.sid
go
--删除测试
drop table [tb]
drop function f_id
go/*--结果
中国
----北京
----上海
----江苏
--------苏州
------------常熟
--------南京
--------无锡
美国
----纽约
----旧金山
加拿大--*/
create table tb(id int,name varchar(10),parent int,depth int)
insert tb select 1 ,'aa',0,1
union all select 2 ,'bb',0,1
union all select 3 ,'cc',1,2
union all select 4 ,'dd',1,2
union all select 5 ,'ee',2,2
union all select 6 ,'ff',2,2
union all select 7 ,'gg',3,3
union all select 8 ,'hh',4,3
union all select 9 ,'ii',5,3
union all select 10,'jj',6,3
go--查询处理函数
create function f_id()
returns @re table(id int,sid varchar(8000))
as
begin
declare @l int
set @l=1
insert @re select id,right(10000+id,4)
from tb where parent=0
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,b.sid+right(10000+a.id,4)
from tb a,@re b
where a.parent=b.id and a.depth=@l
end
return
end
go--调用
select a.id,name=replicate('-',a.depth*2-2)+a.name,parentname=c.name
from tb a
join f_id() b on a.id=b.id
left join tb c on a.parent=c.id
order by b.sid
go--删除测试
drop table tb
drop function f_id/*--结果id name parentname
----------- ---------------- -----------
1 aa NULL
3 --cc aa
7 ----gg cc
4 --dd aa
8 ----hh dd
2 bb NULL
5 --ee bb
9 ----ii ee
6 --ff bb
10 ----jj ff(所影响的行数为 10 行)
--*/
------------------------------------------------------
如下调用即可
select a.id,name=replicate('-',a.depth*2-2)+a.name,parentname=IsNull(c.name, '没有')
from tb a
join f_id() b on a.id=b.id
left join tb c on a.parent=c.id
order by b.sid
go
from tb a
join f_id() b on a.id=b.id
left join tb c on a.parent=c.id
order by b.sid
from tb a
join f_id() b on a.id=b.id
left join tb c on a.parent=c.id
order by b.sid