有关求某类的所有上层分类名称,好像递归

flyncu 2007-03-23 10:38:52
我有一个表strucinfo 其中strucode表示编码 locname表示编码名称 fatherid表其父类编码 slevels表示其级别 如果=1就是说明最顶层了 那么如果我有一个商品编码 怎么得出这个商品的所有分类名呢 sql怎么写?谢谢
...全文
189 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
flyncu 2007-03-23
  • 打赏
  • 举报
回复
谢谢各位!
friendlyFour 2007-03-23
  • 打赏
  • 举报
回复
还是用一个函数好
paoluo 2007-03-23
  • 打赏
  • 举报
回复
--建立測試環境
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
*/
中国风 2007-03-23
  • 打赏
  • 举报
回复
用函数这里有个列子
http://blog.csdn.net/roy_88/archive/2006/12/24/1458449.aspx

34,873

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧