0

I have a nvarchar column that is a file path. For example, the values look like the following:

/Example Folder/Example Subfolder/ Example File

I want to pull out the first directory name (so for this example, I just want:

Example Folder

Any suggestions on how to best extract this in SSMS?

jarlh
  • 42,561
  • 8
  • 45
  • 63
sjade
  • 1
  • Does this answer your question? [Using T-SQL, return nth delimited element from a string](https://stackoverflow.com/questions/19449492/using-t-sql-return-nth-delimited-element-from-a-string) – Thom A Aug 30 '21 at 13:51

4 Answers4

3
Declare @ColumnName nvarchar(300);
Set @ColumnName = '/Example Folder/Example Subfolder/ Example File'

Select SUBSTRING(@ColumnName,2,CHARINDEX('/',@ColumnName,2)-2) as [First Directory Name]

Output:

First Directory Name
----------------------
Example Folder

To suit it to your needs, replace @ColumnName with the ColumnName from the table and add from tableName to the select query.

Teja Goud Kandula
  • 1,462
  • 13
  • 26
0
SELECT SUBSTRING(columnname, 0 , CHARINDEX('/',columnname,2))
FROM tableName

db<>fiddle here

eshirvana
  • 23,227
  • 3
  • 22
  • 38
0

Please try the following generic method.

It is using XML and XQuery to tokenize a string. XML/XQuery data model is based on ordered sequences. Exactly what we need for the task.

Both separator and token's position are parameterized. So, it is very easy to retrieve any token in any position.

SQL

-- DDL and sample data population, start
DECLARE @tbl AS TABLE(ID INT IDENTITY PRIMARY KEY, tokens NVARCHAR(MAX));
INSERT INTO @tbl(tokens) VALUES 
('/Example Folder/Example Subfolder/Example File'),
('/SampleFolder/SampleSubfolder/SampleFile');
-- DDL and sample data population, end

DECLARE @separator CHAR(1) = '/'
   , @position INT = 1;

SELECT *
    , c.value('(/root/r[text()][sql:variable("@position")]/text())[1]', 'VARCHAR(256)') AS token
FROM @tbl
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + 
        REPLACE(tokens, @separator, ']]></r><r><![CDATA[') + 
        ']]></r></root>' AS XML)) AS t(c);

Output

+----+------------------------------------------------+----------------+
| ID |                     tokens                     |     token      |
+----+------------------------------------------------+----------------+
|  1 | /Example Folder/Example Subfolder/Example File | Example Folder |
|  2 | /SampleFolder/SampleSubfolder/SampleFile       | SampleFolder   |
+----+------------------------------------------------+----------------+
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21
0

Simple:

SELECT REPLACE(LEFT(folder, CHARINDEX('/', folder, 2)), '/', '')
SQLpro
  • 3,994
  • 1
  • 6
  • 14