简体   繁体   中英

How can I get the almost last substring from “/” delimited string in 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().

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

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

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM