Search code examples
sqlsql-servert-sqlconcatenationsql-null

How do I concatenate only if not null in SQL Server?


I have this table:

PersonTable

|  id  | name |
---------------
|  10  | Mike |
| NULL | Jane |

I want to select id and name from the table and use concat on id, but only if it's not null, like this:

+------+------+
|  Id  | Name |
+------+------+
| A10  | Mike |
| NULL | Jane |
+------+------+

I've tried the following:

SELECT ISNULL(concat('A', id), NULL) AS id, name FROM PeronTable

But my query returns this:

+-----+------+
| Id  | Name |
+-----+------+
| A10 | Mike |
| A   | Jane |
+-----+------+

Solution

  • Hmmm. You can use + instead of concat():

    select 'A' + convert(varchar(255), id), name
    from t;
    

    convert() (or cast()) is necessary assuming that id is a number and not a string.

    + returns NULL if any argument is NULL; concat() ignores NULL arguments.

    Of course, you can use concat() with a case expression:

    select (case when id is not null then concat('A', id) end), name
    from t;