SQL Server 2017 STRING_AGG function

The STRING_AGG function has been introduced in SQL Server 2017.
 
Below shows a simple example of it in use to comma separate a column of data into a single row:

--declare table
DECLARE @t TABLE (c varchar(10));
--insert some data
INSERT INTO @t(c) VALUES ('one'),('two'),('three'),('four'),('five');
--view data
SELECT c FROM @t;
--old way
DECLARE @old varchar(100);
SELECT @old = COALESCE(@old + ',', '') + c FROM @t;
SELECT @old AS old_way;
--new way
SELECT STRING_AGG(c,',') AS new_way FROM @t;

image1

Leave a Reply