Home > Database > Mysql Tutorial > How to Extract the Last Element from a Forward-Slash Separated String in SQL?

How to Extract the Last Element from a Forward-Slash Separated String in SQL?

Patricia Arquette
Release: 2024-12-30 13:26:14
Original
701 people have browsed it

How to Extract the Last Element from a Forward-Slash Separated String in SQL?

Extracting Last Element from Split String in Database

In a table consisting of strings containing multiple elements separated by forward slashes (/), the objective is to extract the last element from each string. For instance, given the following strings:

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

The desired output should be:

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

SQL Approach

To achieve this in SQL, the following query can be employed:

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

This query works by:

  1. Using the REVERSE() function to reverse the string, which places the last element at the start.
  2. Employing CHARINDEX() with the reversed string to find the position of the last /.
  3. Calculating the starting position of the last element by subtracting the position of the last '/' from the total length of the original string and adding 2 (to account for the position after the '/' and the length of the element).
  4. Using the SUBSTRING() function to extract the last element based on the calculated starting position and length.

This approach effectively extracts the last element from each string by reversing the string, locating the last /, and then using these findings to determine the starting point for the substring extraction.

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

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