SQL Server – Split String into Multiple Columns

splitsql servert-sql

Sorry if this question is very basic, but I just can't figure it out, and couldn't find any good answers.

I have a very long list of files, folders and Sizes. I need to Seperate the folders to columns, that I have a column for each folder.

I have a FilePath as a String (eg folder1\folder2\folder3).
I want to seperate this into multiple Columns:

 First  |  Second  |  Third  |  Fourth  |  ...
folder1 | folder2  | folder3 | NULL     | ...
Foldera | folde rb  | folderc | folderd  |

using cross apply string_split(PATH,'\')as folder
I get Folder1.
using row_Number() I can define wich folder I have in my column, but it is always only 1 column.

Actual Example:

select [Parentpath], [Size], [spl].[value] from Files
cross apply string_split([ParentPath], '\') as [spl]


Parentpath                      || Size   ||  Value
Business\Packets\Data\Archive   || 29334  || Business

Best Answer

This is also not pretty, but it allows for as\many\sub\folders\as\you\may\have.

-- borrowing from Brent:
CREATE TABLE #Files (Parentpath varchar(100), Size int);

INSERT INTO #Files (Parentpath, Size)
  VALUES ('Business\Packets\Data\Archive', 29334),
  ('Coach\Loss\Wharf\Current\Blat\Splunge\More', 7337);

DECLARE @s char(1) = CHAR(92), @sql nvarchar(max) = N'SELECT ParentPath, Size';

SELECT ParentPath, Size, value, rn = ROW_NUMBER() OVER 
  (PARTITION BY ParentPath ORDER BY CHARINDEX(value + @s, ParentPath + @s))
  INTO #x FROM #Files AS f CROSS APPLY STRING_SPLIT(f.ParentPath, @s) AS t;

DECLARE @max int = (SELECT MAX(rn) FROM #x);

SELECT @sql += N',  Folder' + RTRIM(rn) + N' = MAX(CASE WHEN rn = ' 
            +  RTRIM(rn) + N' THEN value END)' 
  FROM (SELECT rn = ROW_NUMBER() OVER (ORDER BY name) FROM sys.all_columns) AS x
  WHERE rn <= @max;

SET @sql += N' FROM #x GROUP BY ParentPath, Size ORDER BY Folder1' 
         +  CASE WHEN @max > 1 THEN N', Folder2' ELSE N'' END + N';';

EXEC sys.sp_executesql @sql;

DROP TABLE #x, #Files;

With this sample data I get the following results:

enter image description here