DROP TABLE IF EXISTS items;
CREATE TABLE items (item varchar(20));
INSERT INTO items VALUES ('apple'),('raspberry');
SELECT STRING_AGG(item, CHAR(13)) AS item_list FROM items;
How do I get a line break between items ?
DROP TABLE IF EXISTS items;
CREATE TABLE items (item varchar(20));
INSERT INTO items VALUES ('apple'),('raspberry');
SELECT STRING_AGG(item, CHAR(13)) AS item_list FROM items;
How do I get a line break between items ?
Your query is working fine on my environment. You need to enable this settings in the management studio:
Tools > Options > Query Results > Results to Grid
It makes no sense for me why, but they have changed the default behavior several SSMS releases ago.
Just put it in the string:
SELECT STRING_AGG(item, '
') AS item_list
FROM items;
One caveat is that the definition of "end of line" depends on the operating system. So, this will insert a different value on Unix versus Windows.
Here is a db<>fiddle.
If using the Management Studio Query Editor, the Results to Grid option cannot implement the carriage return. Switch to Results to Text to see the result set properly.
https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15
SELECT STRING_AGG(item, CHAR(13)) AS item_list FROM items;
You can use print
function for print all output as text
DECLARE @Res NVARCHAR(MAX) = (SELECT STRING_AGG(item, '
') FROM items);
print(@Res)
© 2022 - 2024 — McMap. All rights reserved.
CHAR(13)
is Carriage Return.CHAR(10)
in a Line Feed. ChangeCHAR(13)
toCHAR(10)
? If you want both characters (to be explicit) useCHAR(13) + CHAR(10)
. – VillenageSTRING_AGG(item, CHAR(10))
for linux style? OrSTRING_AGG(item, CHAR(13)+CHAR(10))
for windows style? – Kattitext
are limited to 256 characters per value. For Grid results, CR\LF characters are removed by default on Copy. – Villenage