I would like to talk to you about a new Built-in Function, CONCAT, that comes with SQL Server 2012.
As you know, before SQL Server 2012, we used a method like the following to combine some values and text in SELECT:
1 | SELECT 'One' + ',' + 'Two' + ',' + 'Three' |
If all fields were text as above, this was not a problem. But when we changed the above code as follows, we were getting a Conversion error because INT and VARCHAR did not match.
1 | SELECT 'One' + ',' + 'Two' + ',' + 'Three' + ',' + 12345 |
I’ve sampled this with direct literal values in this example, but you know we’ll get the same error when we try to merge data from fields of VARCHAR and INT data types.
In a practical way, we can use the CONCAT command as follows to merge column values into a single text.
1 | SELECT CONCAT('One', ',', 'Two', ',', 'Three', ',', 12345) |
Thus, you can combine the String and Int fields with the CONCAT function without considering the type of data.
CONCAT also handles very well with NULL values. You don’t need to check with ISNULL or something.
For example, the result returns NULL when you run the following command without using CONCAT.
1 | SELECT 'One' + ',' + 'Two' + ',' + 'Three' + ',' + NULL + 12345 |
However, when using the CONCAT function, the result will return as “One, Two, Three, 12345”.
1 | SELECT CONCAT('One', ',', 'Two', ',', 'Three', ',',NULL, 12345) |