来源:作者: 发布时间:2007-12-26 02:06:37


在实际工作中,经常碰到需要多级目录的情况,例如设计一个论坛,他的版面是分级的,而且为了灵活扩展,这种分级是没有限制的,也就是说设计者,不限制用户设定多少级目录。
针对这种情况,我提出的设计方案如下,先设计如下的table(以sql server为例)
create table [版面表] (
[id] [int] identity (1, 1) not null ,
[版面名称] [varchar] (30) collate chinese_prc_ci_as not null ,
[版面级别] [varchar] (30) collate chinese_prc_ci_as not null ,
[上级版面id] [int] not null
) on [primary]
其中顶级版面的上级版面id就是他自己的版面id
输入如下数据:
id
版面名称
版面级别
上级版面id
1
英语学习
1
1
2
四六级学习
2
1
3
gre
2
1
4
gre作文
3
3
5
gre词汇
3
3
6
gre阅读
3
3
7
gre填空
3
3
8
gre作文互评
4
4
9
gre作文提纲
4
4
10
toefl
2
1
11
toefl作文
3
10
12
toefl听力
3
10
13
toefl阅读
3
10
14
toefl语法
3
10
15
体育
1
15
16
足球
2
15
17
中国足球
3
16
18
世界足球
3
16
19
篮球
2
15
20
cba
3
19
21
nba
3
19
创建如下的存储过程来读取某版面的任何上级版面id
--创建某版面遍历上级目录的存储过程
create procedure traversebyname
@name varchar(30) --版面名称
as
declare @i int --级别循环变量
declare @str varchar(30)--临时字符串变量
set @str=@name--首先设定要查询版面名称的初值
select @i=版面级别 from 版面表--获得版面级别
where 版面名称=@str
set @i=@i-1
create table #tmptable--创建临时表,存放各个版面id
(
iid int identity (1, 1),--临时自动编号,用于排序
itemname varchar(30)
)
while(@i>0)--循环读取上级id
begin
select @str=版面名称 from 版面表
where id
in(select 上级版面id from 版面表
where 版面名称=@str)
insert into #tmptable(itemname) values(@str)
set @i=@i-1
end
--按级别从高到低列出上级版面名称
select itemname from #tmptable order by iid desc
drop table #tmptable
执行该存储过程:
exec traversebyname 中国足球
结果如下:
体育
足球
这样就顺利解决了这种表结构中最难的读取任何上级版面的问题。
|
还没有关于此文章的相关评论!