更新数据库表字段从加入逗号分隔的列表(update a database table field w

2019-08-17 18:56发布

我有两个表命名DistrictsSchools 。 该Districts表格包含一个名为列Schools

我需要填充Schools的列Districts从对应表Schools表,这样在每一行Districts表有一个逗号分隔的从学校名称的值列表Schools表。

我怎样才能做到这一点? 我应该使用UPDATE查询或存储过程?

我只得到尽可能:

SQL小提琴

Districts Table

+------------+------+---------+
| DistrictId | Name | Schools |
+------------+------+---------+
|          1 | a    |         |
|          2 | b    |         |
|          3 | c    |         |
|          4 | d    |         |
+------------+------+---------+

Schools Table

+----------+------------+------------+
| SchoolId | SchoolName | DistrictId |
+----------+------------+------------+
|        1 | s1         |          1 |
|        2 | s2         |          1 |
|        3 | s3         |          2 |
|        4 | s4         |          2 |
|        5 | s5         |          4 |
+----------+------------+------------+

如何需要将输出

+------------+------+---------+
| DistrictId | Name | Schools |
+------------+------+---------+
|          1 | a    | s1,s2   |
|          2 | b    | s3,s4   |
|          3 | c    |         |
|          4 | d    | s5      |
+------------+------+---------+

Answer 1:

的帮助下FOR XML PATHSTUFF来串联值,你可以很容易地更新表District与你期望的结果。

UPDATE  a
SET     a.Schools = b.SchoolList
FROM    Districts a
        INNER JOIN
        (
            SELECT  DistrictId,
                    STUFF((SELECT ', ' + SchoolName
                            FROM Schools
                            WHERE DistrictId = a.DistrictId
                            FOR XML PATH (''))
                        , 1, 1, '')  AS SchoolList
            FROM    Districts AS a
            GROUP   BY DistrictId
        ) b ON A.DistrictId = b.DistrictId
WHERE   b.SchoolList IS NOT NULL
  • SQLFiddle演示


文章来源: update a database table field with comma separated list from join