读书人

关于品种的父与子的查询

发布时间: 2013-08-16 14:29:57 作者: rapoo

关于类别的父与子的查询
实现效果:

工业
汽车
轿车
越野轿车
火车
农业
小麦
玉米
牧业
推车


现在要实现功能是搜索车 like '%车%' 就将所有的车的类别 以及它的所有父级节点全部列出。

id //标识
pid //记录标识ID
name //类别名称

表名称为:TargetClassification


需要写一个存储过程,请各位高手大哥帮忙指点一下,谢谢。


[解决办法]
使用CTE递归遍历层次关系,在微软的示例AdventureWork数据库中
WITH EmployeePath( EmployeeID,ManagerID,LV)
AS
(
SELECT EmployeeID,ManagerID,1
FROM HumanResources.Employee WHERE ManagerID=109
UNION ALL
SELECT A.EmployeeID,A.ManagerID,LV+1 FROM HumanResources.Employee AS A JOIN
EmployeePath AS B ON A.ManagerID=B.EmployeeID
)
SELECT * FROM EmployeePath

读书人网 >SQL Server

热点推荐