sql 示例:如何获取多行结果并将它们放入单个字符串中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 示例:如何获取多行结果并将它们放入单个字符串中相关的知识,希望对你有一定的参考价值。

/* This is one method of using a variable to take a single column result set and return
it as a single VARCHAR string.

You start with code like this:
SELECT description
FROM T_CAMPAIGN
WHERE description like '2018 Individual%'

which will give you a normal results set like this:

description
2018 Individual
2018 Individual Institute
2018 Individual Priorities

however, you can use a varchar variable to concatenate this all into a single string like this:

Single String Results
2018 Individual, 2018 Individual Institute, 2018 Individual Priorities,  

*/

-- declare the @kstring variable
DECLARE @kstring varchar(4000)

-- set the variable to '' (making it no longer NULL - if you don't do this, your results will be NULL)
SELECT @kstring = ''

/* set the value of @kstring to the current value ('') and concatenate the multi-row results from description.
If you start with a single string (in this case ''), concatenating the multi-row results will 
place those results into a single character string.
Using 'SELECT @kstring = @kstring + description from T_CAMPAIGN' will result in all description values being placed
together into a single string with no spaces or delimiters between them.
In the example below, the RTRIM funciton is added around 'description' to trim trailing spaces from the values in description,
and concatenating ', ' adds a comma and a space in-between the values, giving you a nice readable format.
*/
SELECT @kstring = @kstring + RTRIM(description) + ', '
FROM T_CAMPAIGN
WHERE description like '2018 Individual%'

-- select @kstring to see everything placed into a single string
SELECT @kstring AS 'Single String Results'

/*
Results from the code above:
Single String Results
2018 Individual, 2018 Individual Institute, 2018 Individual Priorities,  

*/

以上是关于sql 示例:如何获取多行结果并将它们放入单个字符串中的主要内容,如果未能解决你的问题,请参考以下文章

PHP如何将SQL查询结果转为多维数组,并按查询行输出

从 SQL 中提取一列值并将它们放入数组 VBA [关闭]

在 C# mysql 中获取单个列的值并将其放入文本框中

如何在 SQL Server 中将多行文本连接成单个文本字符串

SQL 语句 如何把多行数据放入一行显示 比如:

如何在 BigQuery SQL 中将字符串列拆分为多行单个单词和单词对?