HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

SQL Server: Getting string before the last occurrence '>'

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
lastthesqlgettingoccurrenceserverbeforestring

Problem

I have column called assocname.

Sample data:

1. FirstParty>Individual:2
2. FirstParty:3>FPRep:2>Individual
3. Incident>Vehicle:2>RegisteredOwner>Individual3


I want to get the string before the last occurrence '>'. Here is the result:

1. FirstParty
2. FirstParty:3>FPRep:2
3. Incident>Vehicle:2>RegisteredOwner


How can I do that ?

Solution

SELECT LEFT(assocname, LEN(assocname) - CHARINDEX('>',REVERSE(assocname)))


So we're reversing it, finding the first '>', then subtracting that from the length to find how far that character is from the beginning. Then take all characters up to that point.

Code Snippets

SELECT LEFT(assocname, LEN(assocname) - CHARINDEX('>',REVERSE(assocname)))

Context

StackExchange Database Administrators Q#157728, answer score: 11

Revisions (0)

No revisions yet.