I have a string (which represents a folder path).
The max number of levels is known (subsubfolder)
The min number of levels is known (root does not contain files).
The foldernames can contain spaces.
There is no indication whether a in the example is a folder or a file………….
I want that string to be split into columns.
CREATE TABLE TESTDATA([path] [nvarchar](max))
INSERT INTO TESTDATA (path) VALUES (N'/a/)
INSERT INTO TESTDATA (path) VALUES (N'/a/ab/filename1)
INSERT INTO TESTDATA (path) VALUES (N'/a/ab/abc/filename2)
INSERT INTO TESTDATA (path) VALUES (N'/a/ab/abc/filename3)
INSERT INTO TESTDATA (path) VALUES (N'/a/ab/abc/abcd/filename4)
INSERT INTO TESTDATA (path) VALUES (N'/a/ac/ac e/filename5)
TESTDATA now looks like
|----------path-----------------|
/a
/a/ab/filename1
/a/ab/abc/filename2
/a/ab/abc/filename3
/a/ab/abc/abcd/filename4
/a/ac/ac e/filename5
but I need it to look like
filename--|--root--|--folder--|--subfolder--|--subsubfolder--|
----------|--------|----------|-------------|----------------|
filename1-|---a----|----ab----|
filename2-|---a----|----ab----|-----abc-----|
filename3-|---a----|----ab----|-----abc-----|
filename4-|---a----|----ab----|-----abc-----|-------abcd-----|
filename5-|---a----|----ac----|-----ac e----|
How would I go about this?
I am thinking I should do something with SUBSTRING and CHARINDEX but I tried a thousand things; never getting it right. It seems SUBSTRING stops searching in a string when that string contains spaces.
Using
CHARINDEXandSUBSTRINGis a good approach. Remember thatCHARINDEXcan take a third parameter that specifies the starting point for searching. Using this, you can find the second/, and third/, and so forth. One way to break down the problem is to use subqueries that build on each other and attack one small piece of the problem at a time. Here is an example that decomposes the filenames into subsub folder level using successive Common-Table Expressions:Demo: http://www.sqlfiddle.com/#!3/e91eb/36
Sample Output:
Note: Removing the
/that I’ve kept in as part of the folder name can be trivially done withSUBSTRING(part, 2, 1000)orSUBSTITUTE(part, '/', '').