SQL recursive query (with cte as)

http://www.cnblogs.com/xqhppt/archive/2011/02/15/1955366.html

2011-02-15 16:41 by Youyou summer  2415  reading,  0  comments,  favorites edit

with cte as
(
select Id,Pid,DeptName, 0 as lvl from Department
where Id = 2
union all
select d.Id,d.Pid,d.DeptName,lvl + 1 from cte c inner join Department d
on c.Id = d.Pid
)
select * from cte
Copy the code
with cte as
(
select Id,Pid,DeptName,0as lvl from Department
where Id =2unionallselect d.Id,d.Pid,d.DeptName,lvl+1from cte c innerjoin Department don c.Id = d.Pid)select*from cte




Copy the code

1 table structure

Pid the DeptName the above mentioned id
- --------- ----------- ------------------------- ------------------------- . 1 0 headquarters 2 . 1 R & D department . 3 . 1 test section . 4 . 1 mass portion . 5 2 group 1 . 6 2 group 2 . 7 . 3 test 1 . 8 . 3 test 2 . 9 . 5 distal group 10 . 5 UTILITY










Copy the code
Pid the DeptName the above mentioned id 
- --------- ----------- ------------------------- ------------------------- . 1 0 headquarters 2 . 1 R & D department . 3 . 1 test section . 4 . 1 mass portion . 5 2 group 1 . 6 2 group 2 . 7 . 3 test 1 . 8 . 3 test 2 . 9 . 5 distal group 10 . 5 UTILITY









Copy the code

2 Results investigative arm of ID = 2 and all subordinate departments at the same level

Pid the DeptName Bank of Latvia LVL the above mentioned id
- --------- ----------- ------------------------ -------------------------- ----------- 2 . 1 R & D 0 . 5 2 group 1 . 1 . 6 2 group 2 . 1 . 9 5 distal group 2 10 5 art 2 ( 5 rows affected)







Copy the code
Pid the DeptName Bank of Latvia LVL the above mentioned id 
- --------- ----------- ------------------------ -------------------------- ----------- 2 . 1 R & D 0 . 5 2 group 1 . 1 . 6 2 group 2 . 1 . 9 5 distal group 2 10 5 art 2 ( 5 rows affected)






Copy the code

Principle 3 (taken from the Internet)

  Recursive CTE that contains a minimum of two queries (also referred to as members). The first query is designated members, designated members only valid query returns a table for recursion foundation or anchor point. The second query is called recursively members, so that the query is called recursive member is recursive CTE name is a reference to the trigger. CTE internal application name can be understood as the result set before a query logically.

Recursive queries without explicit recursion termination condition only when the second recursive query returns an empty result set or exceeded the maximum number of recursive stop recursion. It refers to a maximum number of times a method is to use a recursive MAXRECURION.

Reproduced in: https: //www.cnblogs.com/zhangchenliang/p/3738685.html

Guess you like

Origin blog.csdn.net/weixin_34248705/article/details/93495416
Recommended