The recursive query for SQL Server is the with CTE query

Source: Internet
Author: User
Tags getdate

Table structure

Table Data

SQL as follows

With Lmenu as (select name,id,1 as lv,cast (name as nvarchar (max)) as name1, cast (Row_number () Up (order by GETDATE ()) as N varchar () as OrderID from   Table2 where table2.parentid=0 Union all  Select A.name, a.ID, (b.lv+1) as LV, Cast (REPLICATE ("  , b.lv*2) + a.name as nvarchar (max)) as name1,  cast ((b.orderid+ '. ') + CAST (Row_number () over (Order by GETDATE ()) as nvarchar (5))) as nvarchar (ten)) as   OrderID from   Table2 as a inner j Oin Lmenu as B on a.parentid=b.id) SELECT * from Lmenu  ORDER by   OrderID;

Query Result:

The recursive query for SQL Server is the with CTE 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.