一个有挑战的存储过程!!
这是数据库结构,主要体现父类子类的关系!!
id name parent depth
1 aa 0 1
2 bb 1 2
3 cc 2 3
4 dd 3 4
5 ee 0 1
6 ff 5 2
7 gg 6 3
8 hh 7 4
我想实现的效果:
当id号输入2的时候 name id
aa>bb 1>2
当id号输入4的时候 name id
aa>bb>cc>dd 1>2>3>4
当id号输入7的时候 name id
ee>ff>gg 5>6>7
我想写一个存储过程,当传入不同的id的值的时候,怎么样才能选择出如上的效果!!
问题点数:50、回复次数:5Top
1 楼cccccccchl()回复于 2005-06-01 15:10:13 得分 0
各位大哥大姐帮帮忙啊!!Top
2 楼poolnet()回复于 2005-06-01 15:12:10 得分 0
create procedure test
@iid int,
@sRet varchar(200) output
as
declare @tmpid int
select @sRet=name,@tmpid=parent from tablename where id=@iid
while(@tmpid>0)
begin
select @sRet=name+'>'+@sRet,@tmpid=parent from tablename where id=@tmpid
end
Top
3 楼tangtomtnt()回复于 2005-06-01 15:14:12 得分 0
create ....... , @ID int input...
declare @name varchar(50)
while 0=0
begin
select @Name=Name,@Id=Id into #tmpTable from table where Id=@id
if @Name=null break
end
select * from #tmpTableTop
4 楼cccccccchl()回复于 2005-06-01 15:46:10 得分 0
to poolnet:
谢谢你了,不过还想问一下@sRet 作为输出变量,我在凋用这个存储过程的时候需要传什么值吗??Top
5 楼zjcxc(邹建)回复于 2005-06-01 16:39:04 得分 50
--写函数吧(调用方便)
--处理函数
create function f_pstr(@id int,@isid bit)
returns varchar(8000)
as
begin
declare @re varchar(8000)
if @isid=1
begin
select @re=rtrim(id),@id=parent from tb where id=@id
while @@rowcount>0 and @id<>0
select @re=rtrim(id)+'>'+@re,@id=parent from tb where id=@id
end
else
begin
select @re=rtrim(name),@id=parent from tb where id=@id
while @@rowcount>0 and @id<>0
select @re=rtrim(name)+'>'+@re,@id=parent from tb where id=@id
end
return(@re)
end
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',1,2
union all select 3,'cc',2,3
union all select 4,'dd',3,4
union all select 5,'ee',0,1
union all select 6,'ff',5,2
union all select 7,'gg',6,3
union all select 8,'hh',7,4
go
--调用函数实现查询
--id=2
select name=dbo.f_pstr(2,0),id=dbo.f_pstr(2,1)
union all
--id=4
select name=dbo.f_pstr(4,0),id=dbo.f_pstr(4,1)
union all
--id=7
select name=dbo.f_pstr(7,0),id=dbo.f_pstr(7,1)
go
--删除测试
drop table tb
drop function f_pstr
/*--结果
name id
----------------- ------------
aa>bb 1>2
aa>bb>cc>dd 1>2>3>4
ee>ff>gg 5>6>7
(所影响的行数为 3 行)
--*/Top




