Home > Database > Mysql Tutorial > How to Extract the Last Element from a Delimited String Using SQL?

How to Extract the Last Element from a Delimited String Using SQL?

Mary-Kate Olsen
Release: 2024-12-25 22:14:10
Original
636 people have browsed it

How to Extract the Last Element from a Delimited String Using SQL?

Extracting the Last Element from a Split String

In situations where you have a table containing strings with multiple components separated by delimiters (such as slashes in this example), the task of extracting the last element of each component becomes essential. This can be achieved through various programming techniques.

Utilizing SQL, one effective approach is to employ the CHARINDEX and SUBSTRING functions. The CHARINDEX function locates the position of a specified substring within a string, allowing you to identify the delimiter's presence. The SUBSTRING function then extracts the desired portion from the string.

For instance, if you have a table with the following values:

Articles/Search/ArtMID/2681/ArticleID/2218/Diet.aspx
OurStory/MeettheFoodieandtheMD.aspx
TheFood/OurMenu.aspx
Copy after login

And you wish to extract the last element (the filenames):

Diet.aspx
MeettheFoodieandtheMD.aspx
OurMenu.aspx
Copy after login

You can use the following SQL statement:

SELECT SUBSTRING(string, LEN(string) - CHARINDEX('/', REVERSE(string)) + 2, LEN(string)) FROM SAMPLE;
Copy after login

In this statement:

  • LEN(string): Returns the length of the string.
  • CHARINDEX('/', REVERSE(string)): Searches for the last occurrence of the delimiter '/' in the reversed string. This determines the starting position of the last element.
  • SUBSTRING(string, ..., LEN(string)): Extracts the last element from the string, starting from the position identified by CHARINDEX.

By executing this query, you will obtain the desired results, isolating the last elements of the input strings.

The above is the detailed content of How to Extract the Last Element from a Delimited String Using SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template