简体   繁体   中英

STRING_AGG with line break

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://docs.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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM