2

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().

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
agnieszka
  • 14,897
  • 30
  • 95
  • 113

3 Answers3

11
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
Tomalak
  • 332,285
  • 67
  • 532
  • 628
1

You could replace the '/' with a '.' and use PARSENAME.

Here's a SO answer using it: Split String in SQL

Community
  • 1
  • 1
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
1

Parsename is only good when you have 4 or less delimited pieces....here is my solution:

CREATE FUNCTION Piece(@string as varchar(1000),@delimiter as char(1),@piece as int)
RETURNS varchar(1000)
AS
BEGIN
    declare @Items table (Piece int,Item varchar(8000) NOT NULL)
    declare @return varchar(1000)
    DECLARE @Item As varchar(1000), @Pos As int
    DECLARE @piecenum AS int
    SET @piecenum=1
    WHILE DATALENGTH(@string)>0
        BEGIN
            SET @Pos = CHARINDEX(@delimiter,@string)
            IF @Pos = 0 SET @Pos = DATALENGTH(@string)+1
            SET @Item =  LTRIM(RTRIM(LEFT(@string,@Pos-1)))
            IF @Item<>'' INSERT INTO @Items SELECT @piecenum, @Item
            SET @piecenum=@piecenum+1
            SET @string=SUBSTRING(@string,@Pos+DATALENGTH(@delimiter),1000)
        END
    SELECT @return=Item FROM @Items WHERE Piece=@piece
    RETURN @return
END

so:

select dbo.Piece('a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q',',',10)

results in 'j'

whatever
  • 11
  • 1