Concatenating Full Names in Microsoft SQL Server - sql

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.

Related

Splitting Full Name into First Name and Last Name : (Redshift)

I have a table below with names of the customer
fullname
Ash Ketchum
Mary Joe Keth
John
I want to split it into first and last names
firstname lastname
Ash Ketchum
Mary Joe Keth
John
I referred to this post and tried all the solution but nothing seems to work for me. I already did the same exercise in SQLServer using CHARINDEX() but seems like it's not supported in redshift
, same is the case with SUBSTR()
Simplest way to split human name in postgres?
You should be able to use SPLIT_PART():
SPLIT_PART(fullname, ' ', 1) as first_name,
SPLIT_PART(fullname, ' ', 2) as last_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

how to split a column into multiple value using sql

If I have thousands of rows with data and I would like to find out if the column called "Last
Name " contains both First Name and Last Name (could be middle initial too). What SQL command
do I use ? (SQL Server 2008). Once I find it, how do I split the Last Name field and place
first name or middle initial in their own columns ?
For example:
First Name MI Last Name
John B. Smith
Karen A. Jones
Jane Lawrence
Joan K. Bates
Could it be done in Excel as well ?
You could look for spaces in the last name:
select *
from t
where lastname like '% %';
You could look for rows where the first name is missing:
select *
from t
where firstname is null or firstname = '';
EDIT:
If we assume that the names are "simple" as given in the sample data, you can do:
update t
set firstname = left(lastname, charindex(' ', lastname) - 1),
lastname = right(lastname, charindex(' ', reverse(lastname))),
mi = (case when lastname like '% % %'
then rtrim(ltrim(substring(lastname, charindex(' ', lastname + 1), 2)))
end)
where lastname like '% %' and firstname is null;
This makes lots of assumptions about the formats . . . that there are no complete middle names, that there are no honorics, that there are no suffixes, that there are no multiple spaces together. But if your data is simple, it should work.
Here is an example of the logic in SQL Fiddle.
I would do it in two passes:
-- Set first name
UPDATE names
SET FirstName = SUBSTR(LastName,1,CHARINDEX(' ',LastName) - 1),
LastName = SUBSTR(LastName,CHARINDEX(' ',LastName) + 1, LEN(LastName))
WHERE FirstNAme IS NULL
AND CHARINDEX(' ',LastName) > 0
-- Set middle name
UPDATE names
SET MI = SUBSTR(LastName,1,CHARINDEX(' ',LastName) - 1),
LastName = SUBSTR(LastName,CHARINDEX(' ',LastName) + 1, LEN(LastName))
WHERE MI IS NULL
AND CHARINDEX(' ',LastName) > 0
You may have a few false positives but that should get the vast majority of cases.
I would STRONGLY recommend creating a transaction, doing the updates, doing a SELECT to see the results and rolling back the transaction since the update is not reversible.

CONCAT'ing NULL fields

I have a table with three fields, FirstName, LastName and Email.
Here's some dummy data:
FirstName | LastName | Email
Adam West adam#west.com
Joe Schmoe NULL
Now, if I do:
SELECT CONCAT(FirstName, LastName, Email) as Vitals FROM MEMBERS
Vitals for Joe is null, as there is a single null field. How do you overcome this behaviour? Also, is this the default behaviour in MS SQL Server?
Try
ISNULL(FirstName, '<BlankValue>') -- In SQL Server
IFNULL(Firstname, '<BlankValue>') -- In MySQL
So,
CONCAT(ISNULL(FirstName,''),ISNULL(LastName,''),ISNULL(Email,'')) -- In SQL Server
CONCAT(IFNULL(FirstName,''),IFNULL(LastName,''),IFNULL(Email,'')) -- In MySQL
would return the same thing without the null issue (and a blank string where nulls should be).
Look at CONCAT_WS
For example:
CONCAT_WS('',NULL,"TEST STRING","TEST STRING 2")
Yields
TEST STRINGTEST STRING 2
This is easier than constructing IFNULL around everything. You can use an empty string as the separator.
In mysql isnull wont work some time. try IFNULL(),
CONCAT(IFNULL(FirstName,''),IFNULL(LastName,''),IFNULL(Email,''))
SELECT ISNULL(FirstName,'')+ISNULL(LastName,'')+ISNULL(Email,'') as Vitals FROM MEMBERS
is recommended, but if you are really hooked on CONCAT, wrap it in {fn } and you can use the ODBC function like:
SELECT {fn CONCAT(ISNULL(FirstName,''), ISNULL(LastName,''), ISNULL(Email,''))} as Vitals FROM MEMBERS
If you need first<space>last but just last when first is null you can do this:
ISNULL(FirstName+' ','') + ISNULL(LastName,'')
I added the space on firstname which might be null -- that would mean the space would only survive if FirstName had a value.
To put them all together with a space between each:
RTRIM(ISNULL(Firstname+' ','') + ISNULL(LastName+' ','') + ISNULL(Email,''))
You can always use the CONCAT_NULL_YIELDS_NULL setting..
just run SET CONCAT_NULL_YIELDS_NULL OFF and then all null concatenations will result in text and not null..
If you get (like I do in MySQL):
#1582 - Incorrect parameter count in the call to native function 'ISNULL'
You can replace ISNULL function by COALESCE:
CONCAT(COALESCE(FirstName,''),COALESCE(LastName,''),COALESCE(Email,''))
Stefan's answer is correct.
To probe a little bit deeper you need to know that NULL is not the same as Nothing. Null represents the absence of a value, or in other words, not defined. Nothing represents an empty string which IS in fact a value.
Undefined + anything = undefined
Good database tidbit to hold onto!
Starting from MS SQL Server 2012 it was introduced CONCAT function
and according to MSDN
Null values are implicitly converted to an empty string. If all the
arguments are null, an empty string of type varchar(1) is returned.
so it's enough to use CONCAT without IsNull
CONCAT(FirstName, LastName, Email)
SQL Server does not have a CONCAT function.
(Update: Starting from MS SQL Server 2012 it was introduced CONCAT function)
In the default SQL Server behavior, NULLs propagate through an expression.
In SQL Server, one would write:
SELECT FirstName + LastName + Email as Vitals FROM MEMBERS
If you need to handle NULLs:
SELECT ISNULL(FirstName, '') + ISNULL(LastName, '') + ISNULL(Email, '') as Vitals FROM MEMBERS
In the case of MS Access
Option 1) SELECT (FirstName + " " + LastName + " " + Email) as Vitals FROM MEMBERS
You will get blank result in the case of any field with null.
Option 2) SELECT (FirstName & " " & LastName & " " & Email) as Vitals FROM MEMBERS
You will get Space in place of field with null.
After observing the answers for this question, you may combine all of them into one simple solution
CONCAT_WS(',',
IF(NULLIF(FirstName, '') IS NULL, NULL, FirstName),
IF(NULLIF(LastName, '') IS NULL, NULL, usr_lastname),
IF(NULLIF(Email, '') IS NULL, NULL, Email))
So, in short we use CONCAT_WS to concatenate our fields and separate them with ,; and notice that NULL fields nor EMPTY wont concatenated
NULLIF will check if the field is NULL or EMPTY, a field that contains only spaces or is empty as well, ex: '', ' ') and the output will be either NULL or NOT NULL
IF Will out put the field if it's not NULL or EMPTY