SQL-Server CONCAT case - sql

I have the following exercise:
concatenate first, middle, last name and name suffix to form the
customer’s name in the following format: FirstName [MiddleName.]
LastName[, Suffix]. Note that NULL values should be omitted.
I interpret this as the following scenario (created the table from the image and inserted some values):
Please find my sample data below, name is #TB_Customer
The column CustomerName is the expected result and should be of form
FirstName MiddleName.LastName, Suffix if i have enteries for all
the fields.
MiddleName and Suffix can be optional, so the cases are:
If there is a suffix but not a MiddleName then CustomerName
should be of form Firstname LastName,Suffix
If there is a MiddleName but not a suffix then CustomerName
should be of form FirstName MiddleName.LastName
If both MiddleName and Suffix are null then CustomerName should
be of form FirstName LastName)
This is what i'm getting:
But as you can see the CustomerName case query I wrote doesn't work as expected (please see the cases above with bullets)
The query I wrote to get the CustomerName column is:
SELECT
(case
when (MiddleName is not null and Suffix is not null) then
CONCAT(c.FIRSTNAME,' ', c.MiddleName,'.', c.LASTNAME, ', ',Suffix)
when (MiddleName is null and suffix is null) then
CONCAT(c.FIRSTNAME,' ' ,c.LASTNAME)
when (MiddleName is null and Suffix is not null )then
concat (c.FirstName, ' ', c.LastName, ', ',Suffix )
when (Suffix is null and MiddleName is not null) then
concat (c.FirstName, ' ',MiddleName,'.',LastName)
end
)AS CustomerName
,c.*
FROM #TB_Customer c;
I have 2 questions:
Did I understand the exercise and do i have a good logic?
Where have I made a mistake and what's the correct query?
Using SQL-Server 2012
edit
to recreate my scenario please see the code below (sorry for not linking a fiddle but the website is not responding at my current location)
CREATE TABLE #TB_Customer
(
CustomerID int , --PK
Title varchar(50),
FirstName varchar(50),
MiddleName varchar(50),
LastName varchar(50),
Suffix varchar(50),
EmailAddress varchar(50),
Phone varchar(50),
Gender varchar(50),
Birthdate varchar(50),
--no fk
PRIMARY KEY (CustomerID)
)
insert into #TB_Customer values
('1','Sir','John','Jacob','Adams','St','johnJacobAdams#gmail.com','0677731235','M','1989-04-06'),
('2','Mr.','Russel','Thyrone','Peterson','pr','thyronePeterson#yahoo.com','555-010405','M','1963-02-01'),
('3','Ms.','Anne','Candice','Acola','aca','CandiceA#gmail.com','07408989989','F','1988-05-19'),
('4','Mrs.','Sophia','Veronika','Turner','tvs','SophiaVT#facebook.de','0423423887','F','1983-06-20'),
('5','Ms','Margaret','','Delafleur','','delaMarg#yahoo.co','233223355','Female','1982-02-25'),
('6','Mrs','Jessica','Luana','Cruz','','Jess#yahoo.com','787876631','Female','1922-05-05'),
('7','Mr','Dyrius','','Cruz','dc','dyr33#yahoo.com','0673332211','Male','1987-03-01')
update #TB_Customer
set Gender = 'Male' where Gender = 'M'
update #TB_Customer
set Gender = 'Female' where Gender = 'F'

Something like this should work as well...
SELECT concat(firstname
,CASE WHEN ISNULL(middlename,'') <> '' THEN ' '+middlename+'.'
WHEN ISNULL(middlename,'') <> '' AND ISNULL(suffix,'') = '' THEN '.'
ELSE ' ' END
,lastname
,CASE WHEN ISNULL(suffix,'') <> '' THEN ', '+suffix END)
FROM #TB_Customer
OUTPUT:
John Jacob.Adams, St
Russel Thyrone.Peterson, pr
Anne Candice.Acola, aca
Sophia Veronika.Turner, tvs
Margaret Delafleur
Jessica Luana.Cruz
Dyrius Cruz, dc
John Adams, St

I cant see the error in you query, i know if one of the columns is null, all the others will be, but try this way:
SELECT COALESCE(c.FIRSTNAME,'') + ' ' +
CASE WHEN COALESCE(c.MiddleName,'') = ''
THEN ''
ELSE c.MiddleName + '.'
END
+ COALESCE(c.LASTNAME,'') +
CASE WHEN COALESCE(Suffix,'') = ''
THEN ''
ELSE ', ' + Suffix
END AS CustomerName, c.*
FROM #TB_Customer c;
#Henrik is right, '' and NULL are diferent things

Now that you've given the code, I can see what the error is: The empty string is different from NULL.
So your tests for the presence of a middle name/suffix will always be true.
Either set those fields to NULL, or augment the test to check for NULL or empty strings.

SELECT
STUFF(RTRIM(
CONCAT(' ',
COALESCE(NULLIF(FirstName,'') + ' ', ''),
COALESCE(NULLIF(MiddleName,'') + '.', ''),
COALESCE(NULLIF(LastName,''), ''),
COALESCE(', ' + NULLIF(Suffix,'') , '')
)
), 2, 0,'')
FROM #TB_Customer tc
added the STUFF incase for some strange reason all you have is a Suffix

Related

Cannot resolve collation conflict for column 3 in SELECT statement in SQL Server 2014

I have a table 'CustomerAccount' with the following fields:
AccountNumber
AmountDue
CompanyName
Cust_FirstName
Cust_LastName
Address
I am trying to pull a simple report but I get an error message. I can't seem to figure out what is wrong.
My Code:
SELECT AccountNumber
,AmountDue
--,ISNULL(Cust_LastName, '') + ', ' + ISNULL(Cust_FirstName, '') CustomerName
,CASE WHEN ISNULL(CompanyName, '') = ''
THEN Cust_LastName + ', ' + Cust_FirstName
ELSE CompanyName
END CustomerName
-- Above: This is the line where it gives an error.
-- If there is no Company Name then give the Last and First name of the customer.
,CASE WHEN ISNULL(CompanyName, '') = ''
THEN ''
ELSE Cust_FirstName + ' ' + Cust_LastName
END Attn_To
-- Above: If there IS a Company Name then give the First and Last name of the customer.
,[Address]
FROM CustomerAccount
The Error Message:
Cannot resolve collation conflict for column 3 in SELECT statement.
What I have tried:
,CASE WHEN ISNULL(CompanyName, '') = ''
THEN '' --Cust_LastName + ', ' + Cust_FirstName
ELSE CompanyName
END CustomerName
-- This works but only gives a CompanyName when there is one.
-- But does not give me the customer name when there is no CompanyName
If I try only ,ISNULL(Cust_LastName, '') + ', ' + ISNULL(Cust_FirstName, '') instead of the CASE Statement then it works. I get the LastName, FirstName of the customer.
Here is how I fixed it:
,CASE WHEN ISNULL(CompanyName, '') = ''
THEN Cust_LastName + ', ' + Cust_FirstName
ELSE CompanyName
END COLLATE Latin1_General_CI_AI CustomerName
Thanks to #Aaron Bertrand , #Paul and #DT.

In MS SQL, how to combine varchar and seperate with comma (if both varchar exists)

Hope you guys can help a bit. My challenge is simple but im not sure what way to solve it.
I have 2 varchar fields and I want to combine them AND seperate them with a comma if BOTH fields contains text. Both fields can be null, empty or with text inside.
Firstname | Last name | Result
Not | Sure | Not, Sure
| Sure | Sure
Not | | Not
(null) | Sure | Sure
Not | (null) | Not
(null) | (null) |
Some other databases have the convenient concat_ws() function for this.
You can set up a complicated case. Here is a single expression that does what you want:
select replace(ltrim(rtrim(coalesce(firstname, '') + ' ' + coalesce(lastname, ''))), ' ', ', ')
The idea is that it puts a space between the two names (treating NULL values as empty strings). Then it trims leading and trailing spaces, and replaces spaces with ', '.
Note: This assumes, as in your example, the you have no spaces in the names.
If they can have spaces, a case is a better bet:
select (case when firstname is null then coalesce(lastname, '')
when lastname is null then firstname
else firstname + ', ' + lastname
end)
Something simple like this should work...
...
case
when FirstName IS NOT NULL and FirstName <> '' and LastName IS NOT NULL and LastName <> '' THEN CONCAT(FirstName, ', ',LastName)
when FirstName = '' and LastName IS NOT NULL and LastName <> '' then LastName
when LastName = '' and FirstName IS NOT NULL and FirstName <> '' then FirstName
ELSE coalesce(FirstName, LastName)
end
...

SQL: Combine First Name and Last Name columns but if Null change to 'Name Not Provided'

I'm currently building a simple view and need to combine both the First Name and Last Name columns to create a new Customer column. If a First Name and Last Name are not provided I'd like to change this new combined value to 'Name Not Provided'.
Currently I use a simple select statement:
LastName + ', ' + FirstName AS Customer
which appears to work fine for combing the data but if the data doesn't exist, it will just return ', '. How do I go about changing this so it returns 'Name Not Provided'?
SELECT Customer = CASE WHEN FirstName IS NULL AND LastName IS NULL
THEN 'Name Not Provided'
WHEN FirstName IS NULL AND LastName IS NOT NULL
THEN LastName
WHEN FirstName IS NOT NULL AND LastName IS NULL
THEN FirstName
ELSE LastName + ', ' + FirstName END
FROM dbo.TableName
Demo
SET CONCAT_NULL_YIELDS_NULL ON
SELECT ISNULL(LastName + ', ' + FirstName, 'Name Not Provided') AS Customer
Microsoft's ISNULL() function is used to specify how we want to treat NULL values.
The following query will return a default text if FirstName is NULL.
SELECT (ISNULL(FirstName,'First name is null')) AS Customer

Can someone give me tips on how to use the substring function

I have a query where the first column display name length the second is title or courtesy I have done those but I'm having trouble with my third column. It is supposed to use substring and display first name initial and last name initial can anyone tell me how to add this function to what I already have?
Here is the query
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
(since you used LEN I assume you are using SQL Server)
You mean something like this?
substring(FirstName,1,1) + substring(LastName,1,1)
In general it is like this :
substring(expression, startPosition, lenght)
I would use LEFT() instead of substring.
DECLARE #Employees TABLE (FirstName VARCHAR(25),LastName VARCHAR(25), TitleOfCourtesy VARCHAR(5))
INSERT INTO #Employees
VALUES ('Bob','Brown','Mr.'),
('Olivia','Taylor','M rs.'),
('Grace','Stevens','Ms.'),
('Theodor','Seuss','Dr.');
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name],
CASE Replace(TitleOfCourtesy, ' ','') --Gets rid of any white space
WHEN 'Mr.' THEN 'Mister'
WHEN 'mrs.' THEN 'Miss'
WHEN 'Ms.' THEN 'Miss'
WHEN 'Dr.' THEN 'Doctor'
ELSE ''
END + ' ' + LastName AS title,
CONCAT(LEFT(FirstName,1),'.',LEFT(LastName,1),'.') AS Initials
FROM #Employees
Results:
Length of Employee Name title Initials
-------------------------------------------- -------------------------------- --------
Your full name is 8 character(s). Mister Brown B.B.
Your full name is 12 character(s). Miss Taylor O.T.
Your full name is 12 character(s). Miss Stevens G.S.
Your full name is 12 character(s). Doctor Seuss T.S.

SQL Select Query returns NULL when appending string

In a table, there 3 columns: GivenName, FamilyName, MiddleName. And I have to append all three columns values to output a single column like this
Select Upper(GivenName) + FamilyName + Upper(MiddleName) as PersonName.....
But if value for any one of the column is null then the whole output is Null.
Any way if I can check if any of the column is null before appending? So that it is not appended and others which are not null gets appended.
But I cannot use 'where GivenName is not null, FamilyName is not null' condition.
I just dont want to append the string which is null.
For Ex:
If GivenName = 'Mark',
FamilyName = 'Joseph',
MiddleName is null
Then output should be : MARK Joseph instead of NULL which has not appended MiddleName as it is Null.
(But in SQL it the output is NULL. Try this..
declare #FirstName nvarchar(20);
declare #GivenName nvarchar(20);
declare #MiddleName nvarchar(20);
set #FirstName = 'Steve';
set #GivenName = 'Hudson';
set #MiddleName = null;
select Upper(#FirstName) + #GivenName + UPPER(#MiddleName) => Outputs Null
)
Do this:
Select COALESCE(Upper(GivenName), '') + COALESCE(FamilyName, ' ') + COALESCE(Upper
(MiddleName), '') as PersonName
COALESCE will do a null check on the first parameter. If it is null it returns the second parameter
You can use the isnull function to simply output an empty string if the column is null:
Select Upper(isnull(GivenName, '')) + isnull(FamilyName,'') + Upper(isnull(MiddleName,'')) as PersonName
I'm not entirely sure you should be doing this in the database ... it seems like a presentation layer concern to me.
An way of doing this kind on concatenation is
SELECT ISNULL(FirstName + ' ', '')
+ ISNULL(MiddleName + ' ', '')
+ ISNULL(LastName, '')
And obviously you can use the UPPER and LOWER function where appropriate.
Probably like this
SELECT CONCAT(ISNULL(FirstName, ''),ISNULL(MiddleName, ''),ISNULL(LastName, ''))
AS FullName FROM testtable