This seems a simple question, but it is something I always seem to be up against.
When concatenating two (or more) fields in SQL Server with adding a space between fields like:
SELECT Field1 + ' ' + Field2 FROM table
If Field1
or Field2
may be null
, So we can use ISNULL
to convert it to an empty string but the space remains. One way I have got around this is to add the space before checking if it is null
. And then trimming the ends to allow for empty strings in the fields. E.g:
SELECT LTRIM(RTRIIM(ISNULL(Field1 + ' ','') + ISNULL(Field2, ''))) FROM Table
This handles empty strings in either of the fields but gets very long if there is more than 2 fields to be concatenated in this way.
Is there an easier way?