CharIndex Reverse - find occurrence starting from end of string in TSQL
- Joel Lipman
- Transact-SQL
- Hits: 40482
This is a quick note on finding the last occurrence of a string in a longer string. This has to be in Transact SQL for a SQL Server instance only and not filtered by other code.
Why?
I have a string such as the following (column positions added for demo purposes):
String1.String2.String3.String4 1 5 10 15 20 25 30 -> length = 31
- String1.String2.String3.String4
- 1 5 10 15 20 25 30 -> length = 31
For argument's sake, I'm assigning this string to the variable "haystack".
How?
Perhaps we should determine the position of the last needle first (reverse the haystack string and find needle):