SQL Server 樹形表非輪回遞歸查詢的實例詳解。本站提示廣大學習愛好者:(SQL Server 樹形表非輪回遞歸查詢的實例詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是SQL Server 樹形表非輪回遞歸查詢的實例詳解正文
許多人能夠想要查詢全部樹形表聯系關系的內容都邑經由過程輪回遞歸來查...現實上在微軟在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_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 樹形表非輪回遞歸查詢的實例詳解的相干常識,願望對年夜家有所贊助,假如年夜家有任何疑問迎接給我留言,小編會實時答復年夜家的!