DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Streamlining String Concatenation in SQL Server with CONCAT_WS

In SQL Server, concatenating strings from different columns is a common task, particularly when dealing with names or addresses. While traditional methods like using the + operator or CONCAT function are prevalent, CONCAT_WS offers a more efficient approach. This function stands for "Concatenate With Separator" and simplifies the process by allowing you to define a separator that is automatically inserted between the strings being joined. For example, when merging first and last names from a Customer table:

SELECT
    FirstName + ' ' + LastName AS FullName,
    CONCAT(FirstName, ' ', LastName) AS FullNameConcat,
    CONCAT_WS(' ', FirstName, LastName) AS FullNameConcatWS
FROM Customer
Enter fullscreen mode Exit fullscreen mode

This example demonstrates three methods: using +, CONCAT, and CONCAT_WS. The CONCAT_WS function is particularly useful as it handles NULL values gracefully, not adding the separator if one of the values is NULL, thus avoiding the common pitfalls associated with the other methods.

Top comments (0)