从子节点找到最终的父节点
现有表结构如下:
id pid title
1 0 这是主题贴
2 1 这是跟贴1
3 2 这是跟贴2
4 3 这是跟贴3
此表的树层次为三四层结构.
要求实现通过传入id值,求最顶层的id值,如传入id=4,得出最顶层id=1的主题贴
解如下:
--创建函数
create function 函数名(@keyno int)
returns int
as
begin
declare @pid int,@tmppid int
set @tmppid = (select [pid] from [表名] where [id] = @keyno)
if (@tmppid=0)
set @pid = (select [id] from [表名] where [id] = @keyno)
else
set @pid = [数据库名].[当前数据库用户].[函数名](@tmppid)
return @pid
end
--调用
SET DATEFIRST 1
SELECT [数据库名].[当前数据库用户].[函数名](参数) as 'aa'
--删除函数
DROP FUNCTION 函数名
原文:http://hi.baidu.com/xxfjqb/blog/item/f69bb8deb61c845fcdbf1a53.html
2,从父节点查出所有的子节点
表结构:
KeyId ParentId Name,…………
1 0 父
2 1 子
………………………………
declare @nvarchar(50) KeyId
;//一定要以分号隔开
with T_shi
(
select * from T_table where KeyId=@KeyId
union all
select a.* from T_table as a, T_shi as b where a.parentId=b.keyId
)
select * from T_shi
有了这个涵数,递归简单吧!