5

我有两个名为Districtsand的表Schools。该Districts表包含一个名为 的列Schools

我需要从相应Schools的表格中填充表格的列,以便表格中的每一行都有一个逗号分隔的表格中的学校名称值列表。DistrictsSchoolsDistrictsSchools

我怎样才能做到这一点?我应该使用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      |
+------------+------+---------+
4

1 回答 1

6

在CONCATENATEFOR 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
于 2013-03-20T13:12:56.023 回答