extracting last name from a name string in ORACLE DB - sql

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() should work in this case.
select name, SUBSTRING_INDEX(name,' ',-1) as lastName from Author;

Related

SQL code to get the first letter of two strings

I am trying to get the first letter of a single name and full name.
For example
Name
Alex Patterson
Alex
Output should be
A P
A
Can someone help me with to achieve this?
For recent SQL Server:
SELECT Name, STRING_AGG (initial, ' ') as full_initial
FROM (
SELECT Name, SUBSTRING(value,1,1) as initial
FROM people
CROSS APPLY STRING_SPLIT(name, ' ')
) t
GROUP BY Name

Pulling a section of a string between two characters in SQL, and the section of the string around the extracted section

I have a table that includes names and allows for a "nickname" for each name in parenthesis.
PersonName
John (Johnny) Hendricks
Zekeraya (Zeke) Smith
Ajamain Sterling (Aljo)
Beth ()) Jackson
I need to extract the Nickname, and return a column of nicknames and a column of full names (Full string without the nickname portion in parenthesis). I also need a condition for the nickname to be null if no nickname exists, and so that the nickname only returns letters. So far I have been able to figure out how to get the nickname out using Substring, but I can't figure out how to create a separate column for just the name.
Select SUBSTRING(PersonName, CHARINDEX('(', PersonName) +1,(((LEN(PersonName))-CHARINDEX(')',REVERSE(PersonName)))-CHARINDEX('(',PersonName)))
as NickName
from dbo.Person
Any help would be appreciated. I'm using MS SQL Server 2019. I'm pretty new at this, as you can tell.
Using your existing substring, one simple way is to use apply.
Assuming your last row is an example of a nickname that should be NULL, you can use an inline if to check its length - presumably a nickname must be longer than 1 character? Adjust this logic as required.
select PersonName, Iif(Len(nn)<2,null,nn) NickName, Trim(Replace(Replace(personName, Concat('(',nn,')') ,''),' ','')) FullName
from Person
cross apply (values(SUBSTRING(PersonName, CHARINDEX('(', PersonName) +1,(((LEN(PersonName))-CHARINDEX(')',REVERSE(PersonName)))-CHARINDEX('(',PersonName))) ))c(nn)
The following code will deal correctly with missing parenthesis or empty strings.
Note how the first CROSS APPLY feeds into the next
SELECT
PersonName,
NULLIF(NickName, ''),
FullName = ISNULL(REPLACE(personName, ' (' + NickName + ')', ''), PersonName)
FROM t
CROSS APPLY (VALUES(
NULLIF(CHARINDEX('(', PersonName), 0))
) v1(opening)
CROSS APPLY (VALUES(
SUBSTRING(
PersonName,
v1.opening + 1,
NULLIF(CHARINDEX(')', PersonName, v1.opening), 0) - v1.opening - 1
)
)) v2(NickName);
db<>fiddle

SQL Server 2008 - Remove the parentheses and anything between

I am having a hard time to figure out how to remove the parentheses and anything inside it, plus the space in front. I tried the combination of CharIndex, Substring, and LEFT, but could not get it work correctly.
Here is the example. Let's say I have a very simple table "ContactName" and a column "DisplayName"
Query would be "Select DisplayName FROM ContactName".
In the ContactName table, the data looks like this:
Joe Blow (joe.blow#yahoo.com)
John Deep (jdeep#gmail.com)
(Tim.King#gmail.com) King, Timothy
Richard Harris
Wang, Justin
What I would like to do is removing anything with the parenthesis including the space in front of it if any. For example, "Joe Blow (joe.blow#yahoo.com)" will become "Joe Blow" with NO space, not "Joe Blow ". Also, "(Tim.King#gmail.com) King, Timothy" will become "King, Timothy"
Example of the result would be like this, and NO trailing spaces after the name.
Joe Blow
John Deep
King, Timothy
Richard Harris
Wang, Justin
Maybe I need some kind of RegEx to accomplish this. Please help.
Thanks in advance,
To remove all characters between ( and ) in the string (if they are present), you can use stuff and then a combination of ltrim and rtrim to remove all the trailing and leading spaces.
case when charindex('(',displayname) > 0 and charindex(')',displayname) > 0
then rtrim(ltrim(stuff(displayname,charindex('(',displayname),charindex(')',displayname),'')))
else displayname end
Here is one rather brute force way that works when the parentheses are either at the beginning or end:
select (case when displayname like '(%'
then stuff(displayname, 1, charindex(') ', displayname + ') '), '')
when displayname like '%)'
then left(displayname, charindex(' (', displayname + ' ('))
else displayname
end)
Not an idea solution, but SQL Server doesn't have great support for strings.
Here's another approach:
DECLARE #Table TABLE (DisplayName VARCHAR(100))
INSERT INTO #Table
VALUES ('Joe Blow (joe.blow#yahoo.com)'),
('John Deep (jdeep#gmail.com)'),
('(Tim.King#gmail.com) King, Timothy'),
('Richard Harris'),
('Wang, Justin')
SELECT RTRIM(
LTRIM(
REPLACE(DisplayName,
SUBSTRING( DisplayName,
CHARINDEX('(',DisplayName,1),
((CHARINDEX(')',DisplayName, 1)) - (CHARINDEX('(',DisplayName,1))+1)
),
'')
)
)
FROM #Table

Parsing full name in SQL Server 2008

I know this is a common question and I've reads all the posts just cannot get it to work so here I am. I have a table called PUBLICDATA. In it a table called PEOPLE and a column called NAME.
In the names column are strings of names formatted like:
smith, steve
smith steve a
smith, steve Andrew
smith, steve Andrew robin
What I'd like is a quick and dirty script that I can run that will parse the string in the NAME column and dump the split names into the FIRSTNAME, MIDDLENAME AND LASTNAME columns that also reside in the NAMES table.
ALSO... I have another table (let's say everything is named the same, however the names are like this:
steve smith
steve a smith
steve Andrew smith jr
steve Andrew jackson smith
Both tables do not have salutation and some have Jr, SR, etc... thank you in advance everyone...
PS.. please no self contained examples as I've seen them around but cant get them to work with my situation :(
Well you need a split function. I would split the names using this suggestion: https://gallery.technet.microsoft.com/scriptcenter/T-SQL-Script-to-Split-a-308206f3 and put all of the names in their own table.
I would then recommend that if your data really is always structured last name firstname etc that you match on the length of the last name first. So you take:
SELECT name from your_table WHERE Left(name, Length(last_name_from_name_table))=Length(lastname_from_name_table) AND UPPER(Left(name_from_your_table, length(lastname_from_name_table))=UPPER(lastname_from_name_table)
and blow that out into a series of cases that capture the names you want with cases for first names, jr, etc.
This works like a charm
SELECT LEFT(Name, CHARINDEX(' ', Name)) AS FirstName, CASE WHEN CHARINDEX(' ', Name) <> LEN(Name) - CHARINDEX(' ', REVERSE(Name)) + 1 THEN SUBSTRING(Name, CHARINDEX(' ', Name)+ 1, LEN(Name) - CHARINDEX(' ', REVERSE(Name))-CHARINDEX(' ', Name)) end as middle, RIGHT( Name, CHARINDEX(' ', REVERSE(Name))) AS LastName from a01_parse_test

How to parse a row in SQL into columns (separator-spaces)

I need to parse row (with spaces) into two different columns in SQL. The rows look like that:
FullName
John Mayer
Rajon Jennings
Donna Fraye
Michael Moore
So the expected result is :
Name
John
Rajon
Donna
Michael
Surname
Mayer
Jennings
Fraye
Moore
How can i do that in SQL?
If you have a requirement like First Name should be string before first space and rest everything what follows should go as Last name , you can update two columns as:
Update T
Set T.FirstName = Left(ltrim(rtrim(FullName)), CHARINDEX(' ',ltrim(rtrim(FullName))))
,T.LastName = Right(ltrim(rtrim(FullName)),len(FullName)- CHARINDEX(' ',ltrim(rtrim(FullName))))
From Test T
Check Demo here..
You can use a split function.This function must be created.
Here are some examples :
http://ole.michelsen.dk/blog/split-string-to-table-using-transact-sql/
Split function by comma in SQL Server 2008
If there is only ever 1 space / 2 name and you don't have to cater for names like Vincent van Gough, then a combination of substring and charindex should do.
select substring(fullname, 1, charindex(' ', fullname)) as name,
substring(fullname, charindex(' ', fullname)+1, len(fullname)-charindex(' ', fullname)) as surname
from tbl
This does not cover people with the same first and last name (ie. john john) but will work for rest. Not recommended but is a different solution.
select left(fullname, charindex(' ',fullname)) Name,
replace(fullname,left(fullname, charindex(' ',fullname)),'') Surname
from names
Fiddle