2

I have a simple code below.

Select columnA, columnB, columnC
  From table.

Here is my result.

ColumnA  ColumnB  ColumnC
Apple    G        null
Juice    S        T9

Now, I use the concatenation as follow

Select 
  ColumnA + '_'+ ColumnB + '_' + ISNULL(ColumnC, '') as Name
  From table

My output is as below

Name
Apple_G_
Juice_S_T9

How do I modify the concatenation above so it would show as Apple_G instead of Apple_G_ Basically, I have an extra _ from my result.

1
  • The COALESCE() or ISNULL() functions or conditions could help. When the CONCAT_NULL_YIELDS_NULL option is ON, you have to handle NULL values manually. It is always recommended to do so. Commented May 11, 2016 at 14:25

3 Answers 3

4

Just concatenate the underscore with the nullable column before you apply the IsNull function.

Select 
  ColumnA + '_'+ ColumnB + ISNULL('_' + ColumnC, '') as Name
  From table

This requires the CONCAT_NULL_YIELDS_NULL option being set to ON. - Which it is by default and which is very strongly recommended by Microsoft.

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

3 Comments

I was just about to write this very same thing.
Would that work no matter what ANSI_NULLS is set to? I think I remember there's a setting in which x + null <> null...
@ThorstenDittmar: ANSI_NULLS = OFF allows for equality comparison with NULL. E.g. WHERE Something = NULL. However, I added an info on CONCAT_NULL_YIELDS_NULL which probably is what you were remembering.
0

Use either IIF (SQL Server 2014+) or CASE:

IIF

Select 
    ColumnA + '_' + 
    ColumnB + 
    IIF(ColumnC IS NOT NULL, '_' + ColumnC, '')
From table

CASE

Select 
    ColumnA + '_' + 
    ColumnB + 
    CASE 
        WHEN ColumnC IS NOT NULL THEN '_' + ColumnC
        ELSE ''
    END
From table

Comments

0

You can use COALESCE that it will return the first not null expression

Select COALESCE(ColumnA + '_'+ ColumnB + '_' + ColumnC, ColumnA + '_'+ ColumnB) as Name
  From table

or if you want to customize it in a deeper level

Select COALESCE(ColumnA + '_'+ ColumnB + '_' + ColumnC, 
                ColumnA + '_'+ ColumnB,
                ColumnA ) as Name
  From table

The whole solution relies to the SQL server feature that if any of the concatenated strings is null the complete string becomes null.

3 Comments

+Mr. Vergis, very useful techniques. Thanks a lot
Is x + null == null always? I think I remember there's a setting where this is not the case...
@ThorstenDittmar Yes, there is a setting to change this default behavior but I have never encounter any DB with this setting turned off.

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.