很多人可能想要查詢整個樹形表關聯的內容都會通過迴圈遞迴來查...事實上在微軟在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--通過父節點查詢子節點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
通過子節點查詢父節點查詢結果為:
修改代碼為
--通過子節點查詢父節點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
則結果為:中國北京市丰台區
根據以上可以將這段代碼封裝為一個預存程序
-----預存程序,遞迴擷取樹形地區表字串if exists (select * from sysobjects where name='SP_GetAreaStr')drop proc SP_GetAreaStrgocreate procedure SP_GetAreaStr @id intasdeclare @area varchar(8000)beginWITH 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= @areaend go--exec sp_helptext 'SP_GetAreaStr'--goexec SP_GetAreaStr 28go
查詢結果:中國安徽省宿州市靈璧縣
所用表結構:
部分資料:
以上所述是小編給大家介紹的SQL Server 樹形表非迴圈遞迴查詢的執行個體詳解的相關知識,希望對大家有所協助,如果大家有任何疑問歡迎給我留言,小編會及時回複大家的!