您的位置:首页 > 数据库

sql 根据关系表查找相应的父子类的数据

2010-09-06 14:19 288 查看
Create Table A
(ID Int,
fatherID Int,
Name Varchar(10)
)
Insert A Select 1, NULL, 'tt'
union All Select 2, 1, 'aa'
union All Select 3, 1, 'bb'
union All Select 4, 2, 'cc'
union All Select 5, 2, 'gg'
union All Select 6, 4, 'yy'
union All Select 7, 4, 'jj'
union All Select 8, 7, 'll'
union All Select 9, NULL, 'uu'
union All Select 10, 9, 'oo'
GO
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
create Function [dbo].[GetParent](@ID Int)
Returns @Tree Table (ID Int, fatherID Int, Name Varchar(10))
As
Begin
Insert @Tree Select ID, fatherID, Name From A Where ID = @ID
While @@Rowcount > 0
Insert @Tree Select A.ID, A.fatherID, A.Name From A A Inner Join @Tree B On A.ID = B.fatherID And A.ID Not In (Select ID From @Tree)
Return
End

--測試
Select * From dbo.GetParent(4)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: