很多人可能想要查询整个树形表关联的内容都会通过循环递归来查…事实上在微软在SQL2005或以上版本就能用别的语法进行查询,下面是示例。
--通过子节点查询父节点
WITH
TREE AS(
SELECT * FROM Areas
WHERE id = 6 -- 要查询的子 id
UNION ALL
SELECT Areas.* FROM Areas, TREE
WHERE TREE.PId = Areas.Id
)
SELECT Area FROM TREE
--通过父节点查询子节点
WIT
一、查询当前部门下的所有子部门
WITH dept
AS ( SELECT *
FROM dbo.deptTab --部门表
WHERE pid = id
UNION ALL
SELECT d.*
FROM dbo.deptTab d
INNER JOIN dept ON d.pid = dept.id
)
SELECT *
FROM dept