SQL recursive query for all subordinates

Source: Internet
Author: User

--> 生成测试数据表: [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 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 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 recursive query for all subordinates

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.