--创建数据测试环境--表
create table tb(id int identity(1,1),name varchar(10),parentid int)
insert into tb
select '基础数据',0
union all select '行政区域',1
union all select '教材中心',1
union all select '计算机',3
union all select '项目管理',3
union all select '软件工程',4
union all select '项目管理',4
go
--创建辅助查询的自定义函数
create function f_getmergid(@id int)
returns varchar(1000)
as
begin
declare @re varchar(1000),@pid int
set @re=cast(@id as varchar)
select @pid=parentid from tb where id=@id
while @@rowcount>0
select @re=cast(@pid as varchar)+','+@re
,@pid=parentid from tb where id=@pid
return(@re)
end
go
--调用自定义函数实现查询
select * from tb
where dbo.f_getmergid(id) like dbo.f_getmergid(3)+',%'
go
--删除数据测试环境
drop table tb
drop function f_getmergid
--创建辅助查询的自定义函数
create function f_getmergid(@id int)
returns varchar(1000)
as
begin
declare @re varchar(1000),@pid int
set @re=cast(@id as varchar)
select @pid=parentid from 表名 where id=@id
while @@rowcount>0
select @re=cast(@pid as varchar)+','+@re
,@pid=parentid from 表名 where id=@pid
return(@re)
end
go
--调用这个自定义来实现查询:
select * from 表名
where dbo.f_getmergid(id) like dbo.f_getmergid(3)+',%'
--上面的仅显示3的子,孙子,....,如果要显示3及3的子,孙子...,就用:
select * from 表名
where dbo.f_getmergid(id) like dbo.f_getmergid(3)+'%'
如果知道最多只有几层就好写了,比如最多3层:
Select * from tablename where parentid = 3
union all
select * from tablename where parentid in (Select id from tablename where parentid = 3 )
Union all
Select * from tablename where parentid in (select id from tablename where parentid in (Select id from tablename where parentid = 3 ))