
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,'旧金山'
go
if 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
/*--结果
中国
----北京
----上海
----江苏
--------苏州
------------常熟
--------南京
--------无锡
美国
----纽约
----旧金山
加拿大
--*/
表结构
这种情况可以通过左连接实现
可以看到左连接是以左表为基准,通过关联关系id = pid去找到对应的上级组织记录,所以空的id找不到对应的记录,返回空
有时候我们需要获取某个组织的完整路径 如
部门C/部门C_2/部门C_2_1/部门C_2_1_1
编写存储过程,生成一个临时表tmpLst,按照层级把每一条记录插入到临时表,然后每次从临时表查当前层级的组织,循环去查组织表的上级组织,直到结果ROW_COUNT = 0为止,代表当前层级下的所有组织已经是最后一级
查询到的结果,大家可以自行优化一下显示方式和查询的字段
当然还有另一种方式,从设计上解决
如新加一个唯一约束,把组织的约束定义为 ORG_001_ORG_001_002_ORG_001_003 这样的形式
当需要查询ORG_001所有的下级时,只需要查询约束 like ORG_001% 即可
当需要查询ORG_001_002所有上级时,只需要查询约束 like %ORG_001_002
不过问题在于如果组织的存在架构调整,如,ORG_001_002调整到了 ORG_002下,因为树型结构变化了,直接用like无法查询到正确数据,这个时候要考虑是否允许调整或者调整后修改对应的唯一约束
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)