简体   繁体   中英

extracting last name from a name string in ORACLE DB

I am writing a small query to extract all last names from a bunch of Author name database. Names on file will contain first and middle name, or just first name.

Ex: John Smith John T. Smith

So I cannot search purely by just after the first space... But I know for sure that the lastname should be from the END to the first space from the right side of the string. I don't really care about first name.

This is what I currently have...

select [name], LEFT([name], CHARINDEX(' ', [name] + ' ')-1) as firstName,
SUBSTRING([name], charindex(' ', [name]+' ') + 1, LEN([name])) as lastName
from Author 
;

I am quite new to sql, any help is highly appreciated! Thanks in advance!

EDIT: for those who ever come across this need for help, this line helps:

select substr(t.string,instr(t.string,' ',-1)+1) last_word  

For Oracle DB try this :

WITH t AS
  (SELECT name AS l FROM <your query>
  )
SELECT SUBSTR(l,instr(l,' ',-1)+1,LENGTH(l)) FROM t;

SUBSTRING_INDEX()在这种情况下应该可以工作。

select name, SUBSTRING_INDEX(name,' ',-1) as lastName from Author;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM