很多人可能想要查询整个树形表关联的内容都会通过循环递归来查...事实上在微软在SQL2005或以上版本就能用别的语法进行查询,下面是示例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
--通过子节点查询父节点
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
--通过父节点查询子节点
WITH
TREE AS (
SELECT * FROM Areas
WHERE id = 7 -- 要查询的子 id
UNION ALL
SELECT Areas.* FROM Areas, TREE
WHERE TREE.Id = Areas.PId
)
SELECT Area FROM TREE
|
通过子节点查询父节点查询结果为:
修改代码为
1
2
3
4
5
6
7
8
9
10
11
12
|
--通过子节点查询父节点
declare @area varchar (8000);
WITH
TREE AS (
SELECT * FROM Areas
WHERE id = 6 -- 要查询的子 id
UNION ALL
SELECT Areas.* FROM Areas, TREE
WHERE TREE.PId = Areas.Id
)
select @area= isnull (@area, '' )+Area from Tree order by id
select Area= @area
|
则结果为:中国北京市丰台区
根据以上可以将这段代码封装为一个存储过程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
-----存储过程,递归获取树形地区表字符串
if exists ( select * from sysobjects where name = 'SP_GetAreaStr' )
drop proc SP_GetAreaStr
go
create procedure SP_GetAreaStr
@id int
as
declare @area varchar (8000)
begin
WITH
TREE AS (
SELECT * FROM Areas
WHERE id = @id -- 要查询的子 id
UNION ALL
SELECT Areas.* FROM Areas, TREE
WHERE TREE.PId = Areas.Id
)
select @area= isnull (@area, '' )+Area from Tree order by id
select Area= @area
end
go
--exec sp_helptext 'SP_GetAreaStr'
--go
exec SP_GetAreaStr 28
go
|
查询结果:中国安徽省宿州市灵璧县
所用表结构:
部分数据:
以上所述是小编给大家介绍的SQL Server 树形表非循环递归查询的实例详解的相关知识,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
原文链接:http://www.cnblogs.com/lpz89/archive/2016/10/01/5925672.html