How to combine FirstName, MiddleName, LastName, comma and suffix in SQL Server? - sql-server

I am trying to combine FirstName, MiddleName, LastName then a comma and suffix.
An example here describes this:
Sno. FirstName MiddleName LastName Suffix Result
---------------------------------------------------------------
1. ROBERT NULL SMALLWOOD NULL ROBERT SMALLWOOD
2. KIRK NULL ROBERTS MR KIRK ROBERTS, MR
3. WILLIAM DARRELL WATTENBARGER Jr. WILLIAM DARRELL WATTENBARGER, MR
If there is no Suffix, then comma (,) should not be appended also there should be only one space after every column.
So far I tried
REPLACE(RTRIM(Coalesce(FirstName + ' ', '') + Coalesce(MiddleName + ' ', '') + Coalesce(LastName + ' ', '') + Coalesce(SuffixId + ' ', '')),' ',' ')
Now how should I add a comma before suffix in case if it only exists without using case.
Thanks

You can use CONCAT:
SELECT CONCAT(FirstName,' ',MiddleName + ' ' ,LastName,', '+NULLIF(Suffix,'')) [Result]
FROM dbo.YourTable;

Use ISNULL:
SELECT ISNULL(FirstName + ' ', '') + ISNULL(MiddleName + ' ', '') + ISNULL(LastName + ' ', '') + ISNULL(', ' + SuffixId, '')
FROM My_Table_Name

This is the solution I came up with, please try and see if that worked for you.
create table #FullNameCalculation
(
Sno int not null,
FirstName varchar(10),
MiddleName varchar(10),
LastName varchar(15),
Suffix varchar(5)
)
insert into #FullNameCalculation
(Sno,FirstName,MiddleName,LastName,Suffix)
values
(1, 'ROBERT', NULL,'SMALLWOOD', NULL),
(2, 'KIRK', NULL, 'ROBERTS', 'MR'),
(3,'WILLIAM', 'DARRELL', 'WATTENBARGER', 'JR.'),
(4,NULL,'BARBER','SINK','MS'),
(5,NULL,NULL,'SANDERS','MRS.'),
(6,'SARA',' D','WILLIAMS ',' MS');
SELECT * FROM #FullNameCalculation;
SELECT *,
RTRIM(LTRIM(CONCAT(RTRIM(LTRIM(FirstName)),' ',
RTRIM(LTRIM(MiddleName)),' ',
RTRIM(LTRIM(LastName)),
iif(RTRIM(LTRIM(Suffix)) IS NULL OR RTRIM(LTRIM(Suffix))='','',', '+RTRIM(LTRIM(Suffix)))))) AS FullName
FROM #FullNameCalculation;

I wanted to do something similar and I used COALESCE like OP. Using the suggestion from Mark Adelsberger my query looked like this:
SELECT
RTrim(Coalesce(FirstName + ' ', '')
+ Coalesce(MiddleName + ' ', '')
+ Coalesce(LastName + ' ', '')
+ Coalesce(', ' + Suffix, '')) FullName
FROM dbo.YourTable

Related

Trying to learn SQL

I have a select statement that strings the name together. The issue is that I want to put a period after the middle initial but when it is blank the period is after the firstname. Here is the select
select LTrim(RTrim(FirstName + ' ' + Left(MiddleName,1))) + '. ' + LastName as FullName,
Just add a case
select LTrim(RTrim(FirstName + ' ' + case when isnull(MiddleName,'')='' then else Left(MiddleName,1))) + '. ' end + LastName as FullName,
You could test for the existance of the MiddleName and only include your period if its not null
SELECT
LTRIM(RTRIM(FirstName + ' ' + IIF(ISNULL(MiddleName,'')<>'',LEFT(MiddleName,1) + '.', ''))) + ' ' + LastName as FullName
Use Case statement to check if the string is not empty
select LTrim(RTrim(FirstName + ' ' + Left(MiddleName,1))) +
case when Left(MiddleName,1) <> '' then '. ' else '' end + LastName as FullName,

Can someone please help me understand the case function?

I am working in SQL data base. I have to make two columns. The first column is the length of the employee name(I have that) The second column is title of courtesy and then the last name of employee.
My problem is how do i add the case function to have Ms displayed as miss, mr. as mister and dr as doctor. I do not understand. Any help would be appreciated. Here is the code i have so far:
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name]
, TitleOfCourtesy + LastName AS Title
FROM dbo.Employees
You can do something like this:
select
... your previous things here ...
case TitleOfCourtesy
when 'Mr' then 'Mister '
when 'Ms' then 'Miss '
when 'Dr' then 'Doctor '
else '' end + LastName as Title
try this
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name],
CASE
WHEN TitleOfCourtesy = 'Ms' THEN 'Miss '
WHEN TitleOfCourtesy = 'Mr' THEN 'Mister '
WHEN TitleOfCourtesy = 'dr' THEN 'Doctor ' END + LastName AS Title
FROM dbo.Employees
Thanks all I fixed it I had to add the period after like mr.
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name]
, CASE TitleOfCourtesy
WHEN 'Mr.' THEN 'Mister '
WHEN 'mrs. ' THEN 'Miss'
WHEN 'Ms.' THEN 'Miss '
WHEN 'Dr.' THEN 'Doctor '
ELSE '' END
+ TitleOfCourtesy + LastName
AS title
FROM dbo.Employees

Better method for concatenating columns into a single column

Please consider the following table that holds address details for people:
DECLARE #tbl TABLE
(
userId int IDENTITY(1,1),
address1 nvarchar(100),
address2 nvarchar(100),
address3 nvarchar(100),
addressTown nvarchar(100),
addressCounty nvarchar(100),
addressPostCode nvarchar(10)
);
INSERT INTO
#tbl (address1, address2, address3, addressTown, addressCounty, addressPostCode)
VALUES
('1 Some Road', 'High Hill', 'Battersea', 'London', NULL, 'SW1 2AB'),
('54 Main Street', 'Lowville', NULL, 'Sometown', 'Cumbria', 'AB12 3BA');
SELECT * FROM #tbl;
The output shows this:
userId address1 address2 address3 addressTown addressCounty addressPostCode
----------- --------------- -------------- ------------- ---------------- ------------- ---------------
1 1 Some Road High Hill Battersea London NULL SW1 2AB
2 54 Main Street Lowville NULL Sometown Cumbria AB12 3BA
However, I'd like to concatenate all of the address fields into a single field for the purpose of this statement, so that the results appear as follows:
userId Address
----------- --------------------
1 1 Some Road
High Hill
Battersea
London
SW1 2AB
2 54 Main Street
Lowville
Sometown
Cumbria
AB12 3BA
Please note that this is NOT the same problem as concatenating rows in a single column (using XML etc)!
I have done this using the following approach, but it seems like a whole lot of code for such a small task:
SELECT
userId,
CASE WHEN address1 IS NOT NULL THEN
address1 + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN address2 IS NOT NULL THEN
address2 + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN address3 IS NOT NULL THEN
address3 + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN addressTown IS NOT NULL THEN
addressTown + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN addressCounty IS NOT NULL THEN
addressCounty + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN addressPostCode IS NOT NULL THEN
addressPostCode + CHAR(13) + CHAR(10)
ELSE ''
END as [Address]
FROM
#tbl
Is there a better/faster/more recommended way to achieve this?
You can use ISNULL (or COALESCE if you prefer)
select
ISNULL(Address1 + char(13) + char(10), '') +
ISNULL(Address2 + char(13) + char(10), '') + ...
from #tbl
(Because NULL + something is still NULL)
Thanks to #podiluska's input, here is the final answer that also ensures NULLs are returned if the entire concatenated address is still NULL:
SELECT
userId,
NULLIF(ISNULL(address1 + CHAR(13) + CHAR(10), '') +
ISNULL(address2 + CHAR(13) + CHAR(10), '') +
ISNULL(address3 + CHAR(13) + CHAR(10), '') +
ISNULL(addressTown + CHAR(13) + CHAR(10), '') +
ISNULL(addressCounty + CHAR(13) + CHAR(10), '') +
ISNULL(addressPostCode + CHAR(13) + CHAR(10), ''), '') as [Address]
FROM
#tbl;

How do I get a comma delimited result from result set without using parameters

How do I get a commma delimited result from the following example with no parameters and from a single query:
select FirstName + ' ' LastName from table_of_Names where NameType='game show host'
Bob Barker, Willie Aammes, Steve Allen, Clive Anderson
Thanks.
With parameters (better performance):
DECLARE #list VARCHAR(max)
SELECT #list = COALESCE(#list + ', ' , '') + FirstName + ' ' + LastName
FROM table_of_Names where NameType='game show host'
SELECT #list
Without parameters (not as performant):
select stuff((select ','+ FirstName + ' ' + LastName
FROM table_of_Names where NameType='game show host'
for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '') as NameList
The easiest way I know of is to write a stored procedure that iterates through the result set and appends the comma and space, for all rows except the last.

Correct Amount of Spaces with concatenated person's name in SQL Server

Here is my SQL as I have it now. The first and last name should never be missing because they are required on the interface with validation. However, if the middle initial is missing, I don't want two spaces in the result; I just want one space. I could put a case statement in, but that seems like overkill if SQL already has a function for this purpose. Does anyone know if there is a function for this purpose? What would the code look like?
SELECT ISNULL(contact.firstname, '')
+ ' '
+ ISNULL(contact.middleinitial, '')
+ ' '
+ ISNULL(contact.lastname, '')
FROM dbo.contact
SELECT
ISNULL(contact.firstname, '') +
ISNULL(' ' + contact.middleinitial + ' ', ' ') +
ISNULL(contact.lastname, '')
However, you either should remove ISNULL for firstname, lastname (defined NOT NULL?) or add some trims
SELECT
LTRIM(RTRIM(
ISNULL(contact.firstname, '') +
ISNULL(' ' + contact.middleinitial + ' ', ' ') +
ISNULL(contact.lastname, '')
))
In SQL Server 2012 and up you can use CONCAT function:
SELECT CONCAT(contact.firstname, ' ' + contact.middleinitial, ' ' + contact.lastname)
FROM dbo.contact
If middleinitial is null then appending space to null value will result in null value and CONCAT will skip this null value during concatenation.
SELECT REPLACE(ISNULL(contact.firstname, '') + ' ' + ISNULL(contact.middleinitial, '') + ' ' + ISNULL(contact.lastname, '')
,' ',' ')
FROM dbo.contact

Resources