SQL Server 树形表非循环递归查询

时间:2022-09-19 10:16:29

   很多人可能想要查询整个树形表关联的内容都会通过循环递归来查...事实上在微软在SQL2005或以上版本就能用别的语法进行查询,下面是示例。

--通过子节点查询父节点
WITH
TREE
AS(
SELECT * FROM tstructure
WHERE id = 6 -- 要查询的子 id
UNION ALL
SELECT tstructure.* FROM tstructure, TREE
WHERE TREE.parent = tstructure.id
)
SELECT * FROM TREE

--通过父节点查询子节点
WITH
TREE
AS(
SELECT * FROM tstructure
WHERE parent = 2 -- 要查询的父 id
UNION ALL
SELECT tstructure.* FROM tstructure, TREE
WHERE tstructure.parent = TREE.id
)
SELECT * FROM TREE

来一个我现实中用到的代码吧

WITH tree
AS
(
SELECT * FROM [shar].[t_module] WHERE url='{0}' UNION ALL
SELECT [shar].[t_module].* FROM [shar].[t_module], tree WHERE TREE.fid = [shar].[t_module].id
)
SELECT distinct * FROM tree order by code desc