Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select to get a string between two spaces

I have a field with names in the format DOE JOHN HOWARD or DOE JOHN H.

I need a query to get the string between the two spaces (JOHN in this case).

The SO answer here shows how to do that when the desired substring is between two different strings, but I don't see how to apply something similar when the desired substring is between two instances of the same string (a space in this case).

How can I do that?

like image 203
marky Avatar asked Sep 03 '25 05:09

marky


2 Answers

One way:

select 
left(substring(fld, 
    charindex(' ', fld) + 1, len(fld)), 
    charindex(' ', substring(fld, charindex(' ', fld) + 2, len(fld)))) 
like image 175
Alex K. Avatar answered Sep 04 '25 23:09

Alex K.


There is a somewhat sneaky way you could do this using PARSENAME.

It's intended purpose is to get particular parts of an object/namespace, however, in this case you could use it by replacing the strings with periods first.

E.g.,

SELECT PARSENAME(REPLACE('DOE JOHN HOWARD',' ','.'),2)
like image 21
Scott Avatar answered Sep 04 '25 23:09

Scott