日期:2014-05-19  浏览次数:20521 次

有关求某类的所有上层分类名称,好像递归
我有一个表strucinfo   其中strucode表示编码   locname表示编码名称   fatherid表其父类编码   slevels表示其级别   如果=1就是说明最顶层了   那么如果我有一个商品编码   怎么得出这个商品的所有分类名呢   sql怎么写?谢谢

------解决方案--------------------
用函数这里有个列子
http://blog.csdn.net/roy_88/archive/2006/12/24/1458449.aspx
------解决方案--------------------
--建立測試環境
Create Table strucinfo
(strucode Int,
locname Varchar(10),
fatherid Int,
slevels Int
)
Insert strucinfo Select 1, 'A ', 0 , 1
Union All Select 2, 'A1 ', 1 , 2
Union All Select 3, 'A11 ', 2 , 3
Union All Select 4, 'A12 ', 2 , 3
Union All Select 5, 'A121 ', 4 , 4
Union All Select 6, 'A3 ', 1 , 2
Union All Select 7, 'A31 ', 6 , 3
GO
--建立函數
Create Function GetChildren(@strucode Int)
Returns @Tree Table (strucode Int, locname Varchar(10), fatherid Int)
As
Begin
Insert @Tree Select strucode, locname, fatherid From strucinfo Where strucode = @strucode
While @@Rowcount > 0
Insert @Tree Select A.strucode, A.locname, A.fatherid From strucinfo A Inner Join @Tree B On A.fatherid = B.strucode And A.strucode Not In (Select strucode From @Tree)
Return
End
GO
--測試
Select locname From dbo.GetChildren(2)
Select locname From dbo.GetChildren(6)
GO
--刪除測試環境
Drop Table strucinfo
Drop Function GetChildren
--結果
/*
locname
A1
A11
A12
A121

locname
A3
A31
*/