As you need to capture the middle part and I assume that the part before _ and _ might be random, I believe that the best approach in SQL might be this abomination (exploded the code for better readability):
REPLACE(
REPLACE(
'1_Target_2',
LEFT('1_Target_2', CHARINDEX('_', '1_Target_2')),
''),
RIGHT('1_Target_2', CHARINDEX('_', '1_Target_2')),
'') AS Target
I'm here capturing with LEFT
and RIGHT
parts you don't want and then delete them with REPLACE
. For the use case, you shared I believe it should be more optimized then PATINDEX
.
Depending on the exact use case you might either simplify it with an optional third argument of the CHARINDEX or complicate it with CASE
to make the query safer. You can check examples of those possible extensions in my docs