使用update Query将多行合并为单个值

时间:2015-03-09 18:43:12

标签: sql sql-server

以下是该方案。我有两张桌子。我想使用更新查询将多行值合并为单值。

   DECLARE @Table as Table
    (
        id int,
        name varchar(10)
    )

    insert into @Table values(1,'a')
    insert into @Table values(1,'b')
    insert into @Table values(1,'c')


    select * from @Table


    DECLARE @Table2 as Table
    (
        id int,
        name varchar(10)
    )

    insert into @Table2 values(1,'a')

    update t2 set name = t1.name from @Table2 t2
    inner join @Table t1 on t1.id=t2.id  

    select * from @Table2

我希望通过使用更新查询

从@ Table2输出
    id           name
   -----        --------
    1            a,b,c

1 个答案:

答案 0 :(得分:1)

;WITH Table1 AS (
SELECT t.id 
      , STUFF((SELECT ',' +  name 
               FROM @Table 
               WHERE id = t.id
               FOR XML PATH(''), TYPE)
               .value('.','NVARCHAR(MAX)'),1,1,'') AS name
FROM @Table t
GROUP BY t.id)
UPDATE t2
 SET t2.name = t1.name 
FROM @Table2 t2 
INNER JOIN Table1 t1  ON t1.id=t2.id