2

我有两张表如下所述:

Table1

id | table2_id | value
1  | 1         | AAA
2  | 1         | BBB
3  | 1         | CCC

Table2

id | value
1  | XXXX

并且我想Table2使用来自的组合值进行更新Table1

输出预期Table2

id | value
1  | AAA,BBB,CCC

我该怎么做或者有最好的方法来获得上面解释的预期结果,只是在 sql server 中使用 TSQL?

4

2 回答 2

3

你可以用Common Table Expression这个,

WITH record
AS
(
    SELECT [table2_id],
            STUFF((SELECT ',' + [value]
                    FROM Table1
                    WHERE [table2_id] = a.[table2_id]
                    FOR XML PATH ('')), 1, 1, '')  AS val_list
    FROM    Table1 AS a
    GROUP   BY [table2_id]
)
UPDATE  a
SET     a.value = b.val_list
FROM    table2 a
        INNER JOIN record b
            ON a.ID = b.table2_id
于 2013-05-02T08:14:52.087 回答