0

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 )

1

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for using COALESCE, which complies with the ANSI standard.
1

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.

Comments

0

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.

Comments

0

Probably like this

SELECT CONCAT(ISNULL(FirstName, ''),ISNULL(MiddleName, ''),ISNULL(LastName, ''))
AS FullName FROM testtable

1 Comment

You need not replace NULLs using CONCAT function. Try this select concat(null,'abc',null).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.