我有两个名为DistrictsSchools的表。 Districts表包含名为Schools的列。

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

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

我只知道:

SQL Fiddle

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      |
+------------+------+---------+

最佳答案

借助FOR XML PATH STUFF 来对值进行CONCATENATE,您可以轻松地用所需的结果更新表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 Demo
  • 关于sql - 使用逗号分隔的连接列表更新数据库表字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15524457/

    10-11 18:50