简体   繁体   English

在T-SQL中将多个行字段串联为一列

[英]Concatenating multiple rows fields into one column in T-SQL

I am writing an SQL query in which that I will need to perform a sub select on a table, which will usually return multiple rows. 我正在编写一个SQL查询,其中需要对表执行子选择,该表通常将返回多行。 I need to be able to join together the results of a certain field from all the rows into one field to output. 我需要能够将所有行中某个字段的结果连接到一个字段中以进行输出。 Is this possible, and how? 这有可能,怎么样?

For example, if the SQL query returns 例如,如果SQL查询返回

id | field
1  | test1
2  | test2
3  | test3

I need the outputted field to be "test1 test2 test3". 我需要输出的字段是“ test1 test2 test3”。 Thanks 谢谢

Here's the for xml trick to do that: 这是for xml技巧:

    SELECT  field + ' ' as [text()]
    FROM    YourTable
    FOR XML PATH ('')

This prints: 打印:

test1 test2 test3

It's typically used with an outer apply to execute it once for each row. 它通常与outer apply一起使用,以对每行执行一次。

declare @sample table(id int, field varchar(20))
insert into @sample values(1,'test1')
insert into @sample values(2,'test2')
insert into @sample values(3,'test3')
declare @result varchar(max) set @result = ''
select @result = @result + ' '+field from @sample
select @result

A SQLCLR custom aggregator would be a an alternative (read better) solution SQLCLR自定义聚合器将是替代的(更好的阅读方式)解决方案

As an addition to the existing answers. 作为现有答案的补充。 Try including the COALESCE expression with column name your going to use. 尝试在要使用的列名中包括COALESCE表达式。 This avoids having null values in your concatenated string and avoid your list looking like this. 这样可以避免在串联字符串中包含空值,并避免列表看起来像这样。 Notice the redundant blank space. 注意冗余的空格。

field1 field2   field4 field

Further details can be found here . 可以在此处找到更多详细信息。

GO

DECLARE @tableName VARCHAR(MAX)
SELECT  @tableName = COALESCE(@tableName + ' ' ,'') + Name
FROM    sys.tables
SELECT  @tableName

GO

Try this: 尝试这个:

SELECT RTRIM(field)
  FROM (
                SELECT field + ' ' field
                    FROM <YOUR_TABLE>
                    FOR XML PATH('')
             ) a

it is possible to do with a cursor. 可以用光标做。

declare @field nvarchar(max)
declare @concat nvarchar(max)
set @concat = ''
declare @cursor cursor
set @cursor = cursor for select field from table
open @cursor
fetch next from @cursor into @field
while @@fetch_status = 0
begin
  set @concat = concat(@concat,@field)
  fetch next from @cursor into @field
end

your exercise is to add space between the concatenated strings :-) 您的工作是在连接的字符串之间添加空格:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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