很多人可能想要查詢整個(gè)樹形表關(guān)聯(lián)的內(nèi)容都會(huì)通過(guò)循環(huán)遞歸來(lái)查...事實(shí)上在微軟在SQL2005或以上版本就能用別的語(yǔ)法進(jìn)行查詢,下面是示例。
--通過(guò)子節(jié)點(diǎn)查詢父節(jié)點(diǎn)
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
--通過(guò)父節(jié)點(diǎn)查詢子節(jié)點(diǎn)
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
通過(guò)子節(jié)點(diǎn)查詢父節(jié)點(diǎn)查詢結(jié)果為:
修改代碼為
--通過(guò)子節(jié)點(diǎn)查詢父節(jié)點(diǎn)
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
則結(jié)果為:中國(guó)北京市豐臺(tái)區(qū)
根據(jù)以上可以將這段代碼封裝為一個(gè)存儲(chǔ)過(guò)程
-----存儲(chǔ)過(guò)程,遞歸獲取樹形地區(qū)表字符串
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
查詢結(jié)果:中國(guó)安徽省宿州市靈璧縣
所用表結(jié)構(gòu):
部分?jǐn)?shù)據(jù):
以上所述是小編給大家介紹的SQL Server 樹形表非循環(huán)遞歸查詢的實(shí)例詳解的相關(guān)知識(shí),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
您可能感興趣的文章:- sql server遞歸子節(jié)點(diǎn)、父節(jié)點(diǎn)sql查詢表結(jié)構(gòu)的實(shí)例
- 使用SqlServer CTE遞歸查詢處理樹、圖和層次結(jié)構(gòu)
- 使用SQLSERVER 2005/2008 遞歸CTE查詢樹型結(jié)構(gòu)的方法
- SQLSERVER2005 中樹形數(shù)據(jù)的遞歸查詢
- SQLserver2008使用表達(dá)式遞歸查詢
- 高效的SQLSERVER分頁(yè)查詢(推薦)
- SQL Server SQL高級(jí)查詢語(yǔ)句小結(jié)
- Sql server2005 優(yōu)化查詢速度50個(gè)方法小結(jié)
- SQLserver 實(shí)現(xiàn)分組統(tǒng)計(jì)查詢(按月、小時(shí)分組)
- sqlserver 模糊查詢常用方法
- sql server實(shí)現(xiàn)遞歸查詢的方法示例