Home > Database > Mysql Tutorial > How to Find the Last Occurrence of a Character in SQL Server?

How to Find the Last Occurrence of a Character in SQL Server?

Patricia Arquette
Release: 2025-01-12 12:37:43
Original
868 people have browsed it

How to Find the Last Occurrence of a Character in SQL Server?

SQL Server string operation: efficiently find the last occurrence of a character

Accessing the last index of a substring is critical in various database operations. Although SQL Server does not have a direct LastIndexOf function, there are some clever ways to achieve this functionality.

A common workaround is to reverse the string and use CHARINDEX to search for the last occurrence of a character. However, this approach can be cumbersome and less readable.

Fortunately, SQL Server 2016 introduces some new functions that simplify this task:

Get the substring after the last occurrence of a character:

To get the substring after the last occurrence of a character, you can use the following formula:

<code class="language-sql">select right(db_name(), charindex('_', reverse(db_name()) + '_') - 1)</code>
Copy after login

This expression first reverses the string and then uses CHARINDEX to find the last character. Then, it applies the RIGHT function to extract the substring.

Get the substring before the last occurrence of a character:

Alternatively, if you want the substring before the last occurrence of a character, you can use the following syntax:

<code class="language-sql">select left(db_name(), len(db_name()) - charindex('_', reverse(db_name()) + '_'))</code>
Copy after login

Here, the LEN function determines the total length of the string while the LEFT function is used to extract the required substring.

By using these techniques, you can manipulate strings in SQL Server 2016 more efficiently, making complex operations more straightforward and easier to read.

The above is the detailed content of How to Find the Last Occurrence of a Character in SQL Server?. 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