1

I have a table 'table A' as below and I want to select these data into one column and the result will update table B

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

Result:

Name
-----
a b c
Dale K
  • 25,246
  • 15
  • 42
  • 71
Fate
  • 37
  • 6
  • Please mention the DBMS that are you using. Oracle? MySQL etc.,? – Arun Palanisamy Dec 11 '19 at 06:40
  • I'm using sql server – Fate Dec 11 '19 at 06:41
  • 3
    this topic has been covered hundreds of times here. How to do it in [mysql](https://stackoverflow.com/questions/9456380/aggregate-function-in-mysql-list-like-listagg-in-oracle), [Oracle](https://stackoverflow.com/questions/57629622/how-to-concat-rows-separated-by-a-space-in-oracle), [SQL Server](https://stackoverflow.com/questions/15477743/listagg-in-sqlserver) – hotfix Dec 11 '19 at 06:46
  • SQL server 2017 – Fate Dec 11 '19 at 06:46

3 Answers3

2

Use STRING_AGG()

SELECT
    STRING_AGG(name,' ') Name
FROM
    yourtable
Arun Palanisamy
  • 5,281
  • 6
  • 28
  • 53
1

You can also use stuff() function.

select
   stuff((select (' ' + cast([name] as varchar(30)) )
                      from test2 t2
                        for xml path('')
                    ), 1, 1, '' )
Ed Bangga
  • 12,879
  • 4
  • 16
  • 30
0

Try below query:

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

INSERT INTO TableB(Name)
SELECT REPLACE(@Names,',',' ')
Syed Wahhab
  • 154
  • 1
  • 1
  • 13