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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post