日期:2014-05-19  浏览次数:20928 次

求一树型,逆向递归查询
AdminPart_Id     AdminPart_Name     AdminPart_UpId

6               分站管理员                               11
11           超级管理员                                 0
12           北京分站管理员                         6
13           上海分站管理员                         6
14           北京新闻频道管理员                 12
15           上海新闻频道管理员                   13

要求实现这样的查询     如果     我输入的是       6  
那么结果为

11           超级管理员       0    

如果输入的是     13  
则结果为

11           超级管理员                                 0
6               分站管理员                               11
如果输入的是     15

则结果为  

11           超级管理员                                 0    
6               分站管理员                               11
13           上海分站管理员                         6

------解决方案--------------------
create table ta(AdminPart_Id int, AdminPart_Name varchar(50), AdminPart_UpId int)
insert into ta select 6, '分站管理员 ', 11
union all select 11, '超级管理员 ', 0
union all select 12, '北京分站管理员 ', 6
union all select 13, '上海分站管理员 ', 6
union all select 14, '北京新闻频道管理员 ', 12
union all select 15, '上海新闻频道管理员 ', 13

select * from ta where charindex( ', '+rtrim(AdminPart_Id)+ ', ',dbo.F_se(6))> 0

CREATE FUNCTION F_se (@ID int)
RETURNS varchar(100)
AS
BEGIN
DECLARE @str varchar(100)
set @str= ', '

while(@id <> 0)
select @id=AdminPart_UpId,@str=@str+rtrim(@id)+ ', ' from ta where AdminPart_Id=@id

RETURN(@str)
END
------解决方案--------------------
----创建测试数据
if object_id( 'tbTest ') is not null
drop table tbTest
if object_id( 'fnGetFather ') is not null
drop function fnGetFather
GO
create table tbTest(AdminPart_Id int,AdminPart_Name varchar(20),AdminPart_UpId int)
insert tbTest
select 6, '分站管理员 ', 11 union all
select 11, '超级管理员 ', 0 union all
select 12, '北京分站管理员 ', 6 union all
select 13, '上海分站管理员 ', 6 union all
select 14, '