SQL Server recursive query

Source: Internet
Author: User

--sqlserver recursive query, mainly used to establish a tree structure if object_id (' Categories ') is not NULL DROP table categoriesgocreate table Categories (C     Ategoryid int, CategoryName VARCHAR (), ParentID int) Goinsert into Categories (CategoryID, CategoryName, ParentID) Select 1, ' Books ', NULL union ALL SELECT 2, ' SQL Server ', 1 UNION all select 3, ' ASP.    NET ', 1 union ALL Select 4, ' General ', 2 union ALL Select 5, ' SSIS ', 2 union ALL Select 6, ' TSQL ', 2 UNION ALL    Select 7, ' SSRS ', 2 union ALL Select 8, ' Beginners ', 4 union ALL Select 9, ' Certification Guide ', 4goWITH CTE as (  SELECT 0 as LVL, CategoryID, CategoryName, ParentID, CAST (CategoryID as VARCHAR) as Sort from Categories WHERE ParentID is a NULL UNION all SELECT p.lvl + 1, C.categoryid, C.categoryname, C.parentid, CAST (P.sort + ' /' + CAST (c.categoryid as varchar) as varchar) from Categories C INNER JOIN CTE p on P.categoryid = C.parentid) SELECT CategoryID, SPACE (LVL * 4) + CategorYname as CategoryName, sort, parentid from Cteorder by Sort 


Reproduced in http://beyondrelational.com/modules/2/blogs/28/posts/10486/recursive-cte-and-ordering-of-the-hierarchical-result.aspx

SQL Server recursive query

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.