sql 递归查询所有的下级
生活随笔
收集整理的這篇文章主要介紹了
sql 递归查询所有的下级
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
--> 生成測試數據表: [tb]
IF OBJECT_ID('[Users]')?IS?NOT?NULL ????DROP?TABLE?[Users] GO CREATE?TABLE?[Users] ([userid] [int],[username] [nvarchar](10),[parentUserId] [int],[parentUserName] [nvarchar](10)) INSERT?INTO?[Users] SELECT?'1','admin','0',NULL?UNION?ALL SELECT?'2','aaaaa','1','admin'?UNION?ALL SELECT?'3','bbbbb','2','aaaaa'?UNION?ALL SELECT?'4','ddddd','3','bbbbb' -->SQL查詢如下: ;with?t?as ( ??select?*,level=1?from?Users?where?[parentUserId]=0 ??union?all ??select?a.*,level+1?from?Users a?join?t b?on?a.parentUserId=b.userid ) select?*?from?t?where?[parentUserId]<>0 /* userid????? username?? parentUserId parentUserName level ----------- ---------- ------------ -------------- ----------- 2?????????? aaaaa????? 1??????????? admin????????? 2 3?????????? bbbbb????? 2??????????? aaaaa????????? 3 4?????????? ddddd????? 3??????????? bbbbb????????? 4 (3 行受影響) */總結
以上是生活随笔為你收集整理的sql 递归查询所有的下级的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 郑州日产3.0奥丁正时皮带记号怎么对?
- 下一篇: (provider: 共享内存提供程序,