求一树型,逆向递归查询
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, '北京新闻频道管理员 ', 12 union all
select 15, '上海新闻频道管理员 ', 13
GO
----创建函数
create function fnGetFather(@id int)
returns @t table(AdminPart_Id int,AdminPart_Name varchar(20),AdminPart_UpId int)
as
begin
select @id = AdminPart_UpId from tbTest where AdminPart_Id = @id
while @@rowcount > 0
begin
insert into @t select * from tbTest where AdminPart_Id = @id
select @id = AdminPart_UpId from tbTest where AdminPart_Id = @id
end
return
end
GO
----查询
select AdminPart_Id, AdminPart_Name from dbo.fnGetFather(13) order by 1 DESC
----清除测试环境
drop table tbTest
drop function fnGetFather
/*结果
AdminPart_Id AdminPart_Name
------------ --------------------
11 超级管理员
6 分站管理员
*/
[解决办法]
create table xyz(AdminPart_Id int, AdminPart_Name varchar(40), AdminPart_UpId int)
insert xyz 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
go
create table xyza(id int identity(1,1),a int,b varchar(40),c int)
go
create proc proc_xyz
@id int
as
set nocount on
declare @i int,@flag int,@sql varchar(1000)
select @i=AdminPart_UpId from xyz where AdminPart_Id=@id
if @i is null
begin
set @flag=0
select a,b,c from xyza order by id desc
end
else
begin
insert xyza select * from xyz where AdminPart_Id=@i
set @flag=1
end
if @flag <> 0
exec proc_xyz @i
go
--Call
delete from xyza
go
exec proc_xyz 15