SQL迴圈查詢

2022-01-11 21:17:51 字數 473 閱讀 8679

sql中表示多層關係很多人都喜歡使用同乙個表,在每個子節點指定父節點的方法來實現。

這樣難免會出現迴圈查詢的時候,比如,查詢"亞洲"下面的城市,我們需要先找到國家,才能找到城市。

如果遇到中國,還需要查詢到省份。

找到的解決方法為:

with tab(areacode,areaname,parentareacode) as

(select areacode,areaname,parentareacode from sys_area where areacode=

1union

allselect a.areacode,a.areaname,a.parentareacode from sys_area a,tab b where

b.areacode

=a.parentareacode

)select

*from tab

可以參考一下

SQL 迴圈遍歷

一 遍歷 資料表 select hid into temp from md sheettemplate where sheetstateid 1 declare hid varchar 50 while exists select hid from temp 遍歷臨時表 begin select t...

sql 迴圈,游標

declare userid varchar 50 declare my cursor cursor 定義游標 for select userid from dbo.memberaccount 查出需要的集合放到游標中 open my cursor 開啟游標 fetch next from my c...

sql游標迴圈

declare begindate datetime convert datetime,2019.05.06 09 40 50 enddate datetime getdate idint declare my cursor cursor 定義游標 for select id from dbo.op...