SQL Server tree structure recursion (upward recursion and downward recursion)

Source: Internet
Author: User
--Get the current and following department create proc Getcurrentandunderorg@orgid intasbegin     with    CTE        as (SELECT *, 0 as level from Static_organ  WHERE [email protected]        UNION all        SELECT g.*,level+1 from Static_organ G INNER JOIN CTE on              g . Parentorgan=cte. Organid    )    SELECT * from Cteend

  

--upward recursion   with CTE    as (        SELECT *, levelindex as level from el_departments  WHERE id=170        UNION all        SELECT G.*,g.levelindex as level from El_departments G INNER JOIN CTE on              g.id=cte. ParentID    )

Recursion upward and downward recursively, in fact, is a counter-reverse. The above statement is to use with AS, so the database should be sqlserver2005 above.

SQL Server tree structure recursion (upward recursion and downward recursion)

Related Article

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.