简体   繁体   中英

SQL Server statement to get children using parent id - refactor

I have a table content_folder_tbl that has a list of all folders and sub folders defined with folder_id and parent_id

I want to get all the folders id once I define the root folder_id .

As a workaround I came up with this query :

 select * 
 from content_folder_tbl 
 where folder_id in (select folder_id 
                     from content_folder_tbl 
                     where parent_id = 73 
                     UNION
                     Select folder_id 
                     from content_folder_tbl 
                     where parent_id in (select folder_id 
                                         from content_folder_tbl 
                                         where parent_id = 73)
                     Union
                     Select folder_id 
                     from content_folder_tbl 
                     where parent_id in (Select folder_id 
                                         from content_folder_tbl 
                                         where parent_id in (select folder_id
                                                             from content_folder_tbl 
                                                             where parent_id = 73))
  )

It returns exactly what I want, but it's redundant and works only if I have 3 levels folders.

How to rewrite this query to return values for any level (looks like I need a recursive approach)?

73 is the root folder_id in this case

Example of expected result:

在此输入图像描述

try this one -

;WITH cte AS
(
    SELECT *
    FROM dbo.content_folder_tbl
    WHERE folder_id = 73

    UNION ALL

    SELECT t2.*
    FROM cte t1
    JOIN dbo.content_folder_tbl t2 ON t1.folder_id = t2.parent_id
)
SELECT *
FROM cte
OPTION (MAXRECURSION 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM