Skip to content
Advertisement

Extract the Folder Names and Levels from paths SQL Server / ORACLE

Assuming I have a dataset like this:

Source Data

What I need to do is to make a dataset like this in SQL Server. Any help is appreciated:

Expected Output

Code on pastebin: https://pastebin.com/SjGbD6Cc

CREATE TABLE  "TABLE1" ("FOLDER_ID" VARCHAR2(100 CHAR) ,"FOLDER_NAME" VARCHAR2(100 CHAR) , "PATH" VARCHAR2(100 CHAR) ); 

INSERT INTO TABLE1 VALUES ('1','Folder1','');
INSERT INTO TABLE1 VALUES ('2','Folder1_1','Folder1/Folder1_1');
INSERT INTO TABLE1 VALUES ('3','Folder1_1_1','Folder1/Folder1_1/Folder1_1_1');
INSERT INTO TABLE1 VALUES ('4','Folder1_2','Folder1/Folder1_2');
INSERT INTO TABLE1 VALUES ('5','Folder1_2_1','Folder1/Folder1_2/Folder1_2_1');
INSERT INTO TABLE1 VALUES ('6','Folder1_2_2','Folder1/Folder1_2/Folder1_2_2');

Advertisement

Answer

Perhaps this will help

Example

Select A.Folder_ID
      ,A.Folder_Name
      ,Parent_Folder = Pos2
      ,Lvl           = len(Path)-len(replace(Path,'/',''))
 From Table1 A
 Cross Apply (
                Select Pos1 = reverse(trim(JSON_VALUE(S,'$[0]')))
                      ,Pos2 = reverse(trim(JSON_VALUE(S,'$[1]')))
                 From  ( values ( '["'+replace(replace(reverse(Path),'"','"'),'/','","')+'"]' ) ) A(S)
             ) B

Returns

Folder_ID   Folder_Name     Parent_Folder   Lvl
1           Folder1         NULL            0
2           Folder1_1       Folder1         1
3           Folder1_1_1     Folder1_1       2
4           Folder1_2       Folder1         1
5           Folder1_2_1     Folder1_2       2
6           Folder1_2_2     Folder1_2       2
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement