SQL Reverse Function
Posted by rblumer on Nov-18-2007 under SQL Server
SQL Server has a Reverse function that I have found to be very useful. This function simply returns your expression in a reverse order. It is nice to use if you would like to start your string search from the right. Let’s use the following number as an example: 676777-9099999-86666 .
Now suppose I need to return the last part of the number, 86666.
I can get this result with the following code:
SELECT RIGHT(c.OrderNumber, (CHARINDEX('-', REVERSE(c.OrderNumber)) - 1)) FROM Customers c
The Reverse function would simply return 66668-9999909-777676, which probably is not very useful. However, I can use the CHARINDEX function to obtain the starting position for the first hyphen (’-') . Then I can use the Right function to retrieve the string, which turns out to be 86666.