The CONCAT_WS String Function in SQL Server 2017 is a new function that provides more flexibility for string operations.
CONCAT_WS concatenates a variable number of arguments setting as a delimiter the first argument in the function.
Before checking out some examples of using CONCAT_WS, let’s create a temporary table with some sample data:
CREATE TABLE #tmpTable( id int PRIMARY KEY, code VARCHAR(50), descr VARCHAR(100) ); GO INSERT INTO #tmpTable VALUES (1,'code1','descr1'), (2,'code2','descr2'), (3,'code3','descr3'), (4,'code4','descr4'), (5,'code5','descr5'); GO
Let’s take a look at the sample data we have just created:
Now let’s concatenate the columns in each record in the above table by running the below query:
SELECT CONCAT_WS('-',id,code,descr) FROM #tmpTable; GO
And here are the results:
As you can see, all values in each record have been concatenated and they now have the character ‘-‘ as a delimiter.
Another use of CONCAT_WS is that you can easily generate CSV files. Based on our example, let’s export the table’s contents in CSV format using semicolon (;)
So, prior to running the query, first in Management Studio query window, right-click and select to display the results of the query to Text (Results To –> Results to Text).
OK, now let’s run the query:
SELECT CONCAT_WS(';',id,code,descr) as ConcatValue FROM #tmpTable; GO
And here are the results of the above query:
As you can see, the concatenated strings are delimited with semicolon and you can easily write the results into a new file, thus automatically creating a CSV file.
CONCAT_WS is a handy new string function in SQL Server and Azure SQL Database. It provides additional flexibility when it comes to string manipulation processes in SQL Server. In subsequent posts, we will explore more programmability features in SQL Server 2017 and Azure SQL Database.
Rate this article:
Reference: SQLNetHub (https://www.sqlnethub.com)