T-SQL Tutorial T-SQL Advanced Database Management T-SQL References

T-SQL CONCAT_WS() Function



The T-SQL (Transact-SQL) CONCAT_WS() function is used to concatenate two or more expressions together and adds a separator between each of the concatenated expressions. This function may have one or more expressions. Note that, if any of the expressions is a NULL, this function ignores NULL values during concatenation, and does not add the separator between NULL values.

Syntax

CONCAT_WS(separator, expr1, expr2, ... expr_n)

Parameters

separator Required. Specify the separator which will be added between each of the concatenated expressions.
expr1, expr2, ... expr_n Required. Specify the expressions to concatenate together.

Return Value

Returns the concatenated string.

Example 1:

The example below shows the usage of CONCAT_WS() function.

SELECT CONCAT_WS(' ', 'SQL', 'Tutorial');
Result: 'SQL Tutorial'

SELECT CONCAT_WS(' ', 'Learning', 'SQL', 'is', 'fun!.');
Result: 'Learning SQL is fun!.'

SELECT CONCAT_WS(', ', 10, 20, 30, 40);
Result: '10, 20, 30, 40'

SELECT CONCAT_WS(' = ', 'Sum', 25 + 25);
Result: 'Sum = 50'

SELECT CONCAT_WS(', ', 10, 20, NULL, 40);
Result: '10, 20, 40'

Example 2:

Consider a database table called Employee with the following records:

EmpIDFirstNameLastName
1JohnSmith
2MarryKnight
3JoWilliams
4KimFischer
5RameshGupta
6HuangZhang

In the query below, the CONCAT_WS() function is used to concatenate records of column FirstName and column LastName.

SELECT *, CONCAT_WS(' ', FirstName, LastName) AS FullName FROM Employee;

This will produce the result as shown below:

EmpIDFirstNameLastNameFullName
1JohnSmithJohn Smith
2MarryKnightMarry Knight
3JoWilliamsJo Williams
4KimFischerKim Fischer
5RameshGuptaRamesh Gupta
6HuangZhangHuang Zhang

❮ T-SQL Functions