-1

There is no default split function in SQL Server 2012 that I'm using.

I want to split the string (ex: /Folder1/Folder2/) by /.

  • if string is /Folder1/ then output should be Folder1,
  • if string is /Folder1/Folder2/ then output should be Folder2,
  • if string is /Folder1/Folder2/Folder3/ then output should be Folder3.
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
Liam neesan
  • 2,282
  • 6
  • 33
  • 72
  • What version of SQL server are you on? – Reno Sep 30 '18 at 09:24
  • @Reno Sql server 2012 – Liam neesan Sep 30 '18 at 09:25
  • 1
    A combination of the [REVERSE](https://learn.microsoft.com/en-us/sql/t-sql/functions/reverse-transact-sql?view=sql-server-2017), [CHARINDEX](https://learn.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql?view=sql-server-2017), and [SUBSTRING](https://learn.microsoft.com/en-us/sql/t-sql/functions/substring-transact-sql?view=sql-server-2017) functions will get you there. – TT. Sep 30 '18 at 09:29
  • This question has been answered before in many different flavours: https://stackoverflow.com/questions/2647/how-do-i-split-a-string-so-i-can-access-item-x?rq=1 – Alex Sep 30 '18 at 09:35
  • @TT I found the answer with your help `SELECT REVERSE(SUBSTRING(SUBSTRING(REVERSE('/Folder1/Folder2/'),2,len(REVERSE('/Folder1/Folder2/'))),1,charIndex('/',SUBSTRING(REVERSE('/Folder1/Folder2/'),2,len(REVERSE('/Folder1/Folder2/'))))-1))` – Liam neesan Sep 30 '18 at 09:43

1 Answers1

1

Try this:

declare @tbl table (path varchar(100));
insert into @tbl values
('/Folder1/'),
('/Folder1/Folder2/'),
('/Folder1/Folder2/Folder3/');

select *, 
       replace(substring(path, len(path) - charindex('/', reverse(path), 2) + 1, 1000), '/', '')
from @tbl
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69