Antoine Pelletier Antoine Pelletier - 6 months ago 24
SQL Question

SQL server, concat nvarchar when some are null

Probably a question of null values...

I would like to do just like in C# :

string s3 = s2 + ' ' + s1;


witch could be read like :

'hello world' = 'hello' + ' ' + 'world


But in SQL, some of my NVARCHAR(1) are null, so it sometimes look like :

null = 'hello + ' ' + null


And in this case i would rather have :

'hello ' = 'hello' + ' ' + null


I don't see, is there a simple way to do that ?

Answer

Use COALESCE() or ISNULL():

SELECT COALESCE(S2, '') + ' ' + COALESCE(S1, '')

Or:

SELECT ISNULL(S2, '') + ' ' + ISNULL(S1, '')
Comments