Skip to content
Advertisement

SQL: Substring until second character starting from right keeping left values

I have this filename AAAA_BBBBB_CC_HDDD_HGGG.csv and I’m trying to keep the values after the second underscore starting from the right.

So i want to keep any values just before _HDDD_HGGG.csv

This is my code:

And this is the returned value:

Instead of being AAAA_BBBBB_CC.

Does anyone has a clue for this?

Advertisement

Answer

You are taking a SUBSTRING from 1 till your CHARINDEX while your string is reversed. Either reverse your string again or use LEN to find the length of your string like so:

p.s.: Added a second +1 to remove the “_” between CC and HDDD

p.p.s: CHARINDEX is a SQL Server function which I assume is what you are actually using. The MySQL equivalent would be POSITION, the equivalent for LEN would be LENGTH

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement