6

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 enter image description here 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: enter image description here

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'
10
  • 1
    @DanBracuk please see line 5 from the expected result. That is not ok. Also line 7
    – CM2K
    Nov 17, 2015 at 15:40
  • 2
    How are we supposed to see that your query doesn't work, when you don't show the result? Furthermore you list three cases and your code has four, and in a rather strange order. Nov 17, 2015 at 15:40
  • So your "Expected result" is not actually what you expect, but what you actually get? Nov 17, 2015 at 15:42
  • 1
    @Henrik there are 4 cases, the first one is the scenario in which every field is not null. The expected value of the column is in the bullet list. Will edit and put the 4th case with a bullet
    – CM2K
    Nov 17, 2015 at 15:42
  • 1
    Do you realize that you are checking for NULL but there is not a single NULL anywhere in your sample data?
    – Sean Lange
    Nov 17, 2015 at 15:46

4 Answers 4

11

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
2
  • marked as answer for offering a working solution which doesn't use coalesce (was trying to do it only with cases, thanks)
    – CM2K
    Nov 17, 2015 at 16:09
  • @Doolius WHEN ISNULL(middlename,'') <> '' AND ISNULL(suffix,'') = '' THEN '.', will this condition be evaluated ever? I ask this because if middlename is NOT NULL then the first WHEN condition will be executed always. May 15, 2018 at 18:51
5

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

3
  • this gives for line 5 (please see the 2nd picture). Margaret .Delafleur, Should give Margaret Delafleur , without the dot or the comma
    – CM2K
    Nov 17, 2015 at 15:48
  • Edited, but the picture show a dot before Delafleur Nov 17, 2015 at 15:49
  • this works great, thanks. Accepted Doolius' answer because it doesn't use coalesce, was looking only for cases (but great solution, has my upvote)
    – CM2K
    Nov 17, 2015 at 16:11
1

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.

5
  • Thank you for your answer, I don't know how to "check for NULL or empty strings" . Ideas?
    – CM2K
    Nov 17, 2015 at 15:52
  • 2
    You check for NULL with "field IS NULL" and for empty strings with "field = ''", and combine those with AND or OR (and possibly some parentheses) just like you already have. Nov 17, 2015 at 15:57
  • tried it like this, doesn't work: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 or MiddleName = '') and (suffix is null or suffix = '') then CONCAT(c.FIRSTNAME,' ' ,c.LASTNAME) when (MiddleName is null or MiddleName = '' ) and (Suffix is not null )then concat (c.FirstName, ' ', c.LastName, ', ',Suffix ) when (Suffix is null or Suffix = '')and MiddleName is not null then concat (c.FirstName, ' ',MiddleName,'.',LastName) end )AS CustomerName ,c.* FROM #TB_Customer c;
    – CM2K
    Nov 17, 2015 at 16:51
  • sorry for making it messy, but fiddle doesn't work for me here. Did I get your point?
    – CM2K
    Nov 17, 2015 at 16:53
  • It's really hard to read, but I don't think that will work. As far as I can see, the case where both the MiddleName and Suffix is '' you will hit the first case - but where you have added a check for the empty string it looks correct. Nov 18, 2015 at 10:41
1
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

2
  • this works great, thanks. Accepted Doolius' answer because it doesn't use coalesce, was looking only for cases (but great solution, has my upvote)
    – CM2K
    Nov 17, 2015 at 16:11
  • 1
    @CM2K Thanks.. you might want to look at this also.. it forms the name the way you'd actually want to see it if you were creating some sort of name label.. sqlfiddle.com/#!6/76d65/1 Only using periods for middle initials and such
    – JamieD77
    Nov 17, 2015 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.