SQL Server 2008 - Remove the parentheses and anything between - sql

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

Related

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

Concatenating Full Names in Microsoft SQL Server

Suppose I have a table with the following information
Title FirstName MiddleName LastName Suffix
======|============|=============|============|======
Mr. John Fitzgerald Kennedy NULL
NULL John NULL Doe III
I want to create a query to output the full name of the above information. For example, I want the output to look like
Mr. John Fitzgerald Kennedy
John Doe, III
I was thinking of using the concat() function, but I am unsure how to go about this to ensure I don't have extra spaces or hanging commas in the names.
This is a little tricky. SQL Server 2017+ supports concat_ws(). However, you still need a comma for the suffix. Forturnately, concat() ignores NULLs:
select concat(concat_ws(' ', title, firstname, middlename, lastname),
', ' + suffix
)
Earlier versions require a bit more work to avoid multiple spaces when there are NULL values:
select ltrim(concat(' ' + title,
' ' + firstname,
' ' + middlename,
' ' + lastname,
', ' + suffix
)
)
This uses the fact that + returns NULL when an argument is NULL. But, concat() ignores it.
Note: Neither probably does what you want if all the names are NULL but the suffix is present. However, I doubt that is an issue in your data.
Here is a db<>fiddle.

Adding comma after first word in column

I have a table called people and a column called NAME which has last first middle (if exists) . so SMITH JOHN J I'd like to add a comma after first word so it updates to SMITH, JOHN J
I tried running this but it blew up:
update people
set name = (CHARINDEX(' ', 0), 0, ',')
I know I'm close but it's eluding me :(
You can use STUFF() along with CHARINDEX() and LEFT() for this:
update people
set name = STUFF(name,1,CHARINDEX(' ',name )-1,LEFT(name ,CHARINDEX(' ',name )-1)+', ')
WHERE CHARINDEX(' ',name) > 0
Might add a WHERE to ensure there is a space in the name so it doesn't error, or a CASE expression.
Could also use REPLACE() with CHARINDEX() and LEFT():
REPLACE(name,LEFT(name,CHARINDEX(' ',name)-1),LEFT(name,CHARINDEX(' ',name)-1)+',')

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

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