1

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:

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
IndieTech Solutions
  • 2,527
  • 1
  • 21
  • 36

1 Answers1

3

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)
Devart
  • 119,203
  • 23
  • 166
  • 186