Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the almost last substring from "/" delimited string in T-SQL?

Tags:

sql

t-sql

If I've got a string that consists of other strings delimited with "/" character (xxx...xxx/xxx/xxxx) how can I get the last and the almost last (the one before last) part with t-sql? It should probably be some combination of charindex() and right().

like image 519
agnieszka Avatar asked Dec 06 '25 17:12

agnieszka


1 Answers

declare @s varchar(50);
set @s = 'aaaaa/bbbbb/ccccc/ddddd/eeeee'

/* last one: */
select
    RIGHT(@s, CHARINDEX('/', REVERSE(@s)) - 1)

/* penultimate one */
select
    RIGHT(
      LEFT(@s, LEN(@s) - CHARINDEX('/', REVERSE(@s))), 
      CHARINDEX('/', REVERSE(
        LEFT(@s, LEN(@s) - CHARINDEX('/', REVERSE(@s)))
      )) - 1
    )

The "last one" is pretty straightforward, no explanation needed.

The "penultimate one" is essentially equal to the "last one", with all occurrences of @s replaced with:

LEFT(@s, LEN(@s) - CHARINDEX('/', REVERSE(@s)))

which produces 'aaaaa/bbbbb/ccccc/ddddd'

To check whether there are enough slashes in the string for this expression to succeed, you could do

CASE WHEN LEN(@s) - LEN(REPLACE(@s, '/', '')) >= 2 
     THEN /* expression here */
     ELSE /* error value here */
END
like image 90
Tomalak Avatar answered Dec 08 '25 09:12

Tomalak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!