功能说明:
1-查询某个节点的所有父级节点
2-按树输出路径
例子:假设表名是 TREE_TABLE , 节点ID字段名是 t_id , 节点父级字段名是 t_pid
-- 查询 节点ID=20 的父级路径
DECLARE @id INT = 20 ;
WITH tab AS (
SELECT t_pid pid , 0 no FROM TREE_TABLE WHERE t_id =@id
UNION ALL
SELECT t_pid pid , tab.no+1 no FROM tab ,TREE_TABLE WHERE t_id =pid
)
SELECT (SELECT CONCAT(t_id,',') FROM tab LEFT JOIN TREE_TABLE ON t_id=pid WHERE pid>0 ORDER BY no DESC FOR XML PATH('')) 'path';
执行SQL,输出路径
抄作业提示:把上面例子有标颜色的 表名、字段名 替换为自己的表结构就可以了