Select 来自一列的多个数据并将合并结果更新为另一列 table

Select multiple data from one column and update the combine result to another table

我有一个 table 'table A' 如下,我想 select 这些数据到一列,结果将更新 table B

+-----------+
| ID | Name |
+-----------+
| 1  |a     |
+-----------+
| 2  |b     |
+-----------+
| 3  |c     |
+-----------+

结果:

Name
-----
a b c

使用STRING_AGG()

SELECT
    STRING_AGG(name,' ') Name
FROM
    yourtable

您也可以使用stuff()函数。

select
   stuff((select (' ' + cast([name] as varchar(30)) )
                      from test2 t2
                        for xml path('')
                    ), 1, 1, '' )

尝试以下查询:

Declare @Names varchar(max)
SELECT @Names = COALESCE(@Names + ', ', '') + Name 
FROM TableA

INSERT INTO TableB(Name)
SELECT REPLACE(@Names,',',' ')