id name parentid
1 基础数据 0
2 行政区域 1
3 教材中心 1
4 计算机 3
5 项目管理 3
6 软件工程 4
7 项目管理 4
我想取出所有属于3的孩子的记录!
--------------------------------------------------------------------------------------------
1 基础数据 0
2 行政区域 1
3 教材中心 1
4 计算机 3
5 项目管理 3
6 软件工程 4
7 项目管理 4
我想取出所有属于3的孩子的记录!
--------------------------------------------------------------------------------------------
--创建辅助查询的自定义函数
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)+'%'