Oracle - Using SUBSTR to deisplay first letter of middle initial from full name field

I am using Oracle SQL.  I needed to split a full name field into separate columns for the last, first and middle initial.
The name field is always formatted with last name, first name middle (last comma first space middle)

I've got the last and first name columns but having trouble getting the middle initial column displaying the correct letter.  The middle name field can be entered as the full middle name or as the middle initial.

Full name Smith, James A will show display correctly
BUT if the middle name was entered as Smith, James Adam then the last letter of the middle name is displayed as "m” rather than the first letter "A".

I'm currently using this code to get the names separated:

regexp_substr(full_name,'[^,]+',1,1)  Last_Name
regexp_substr(full_name,'[^, ]+',1,2)  First_Name

substr(regexp_substr(full_name,'[^ ]+',1,3),-1)  Middle_Initial

The file will need some manual clean up,so 2 first names or extra spaces that kind of thing will be dealt with manually.
Who is Participating?
Geert GConnect With a Mentor Oracle dbaCommented:
try it with \w

with d as (  
  select 'Smith, James Adam' name from dual
  union all select 'Smith, James M' from dual)
select name, regexp_substr(name, '\w+') lastname, regexp_substr(name, '\w+', 1, 2) firstname, substr(regexp_substr(name, '\w+', 1, 3), 1, 1) initial
from d;  

Open in new window

Mark GeerlingsDatabase AdministratorCommented:
Or, just use this:
substr(regexp_substr(full_name,'[^ ]+',1,3),1)  Middle_Initial
instead of this:
substr(regexp_substr(full_name,'[^ ]+',1,3),-1)  Middle_Initial
to get the middle initial.

The "-1" in your code for "substr" tell "substr" to start at the end of the string and work backwards, returning the first character it finds.
As an alternative to regular expressions -
select substr(fullname,instr(fullname,' ',-1) + 1,1) from yourtable;
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.