Wednesday, September 25, 2019

CONCAT_WS and STRING_AGG are new ways to CONCAT with SQL Server 2017!

The _WS stands for "with separator" and something like this...

DECLARE @counter INT
SET @counter = 0
WHILE @counter <= 5
BEGIN
   PRINT CONCAT_WS(@counter, 'x', 'y', 'z')
   SET @counter = @counter + 1
END

 
 

...gives us something like this:

x0y0z
x1y1z
x2y2z
x3y3z
x4y4z
x5y5z

 
 

Do you see how the separator was put into the strings? A bit more elaborately the _AGG does "aggregation" from a query. Observe:

DECLARE @container TABLE
(
   contents nvarchar(15) not null
)
DECLARE @counter INT
SET @counter = 0
WHILE @counter <= 5
BEGIN
   INSERT INTO @container(contents) VALUES (CONCAT_WS(@counter, 'x', 'y', 'z'))
   SET @counter = @counter + 1
END
DECLARE @conversion nvarchar(1) = CAST(@counter AS varchar(1))
SELECT STRING_AGG(contents, @conversion) FROM @container

 
 

We get:

x0y0z6x1y1z6x2y2z6x3y3z6x4y4z6x5y5z

No comments:

Post a Comment