【问题标题】:SQL SERVER: concatenate node values of XML columnSQL SERVER:连接 XML 列的节点值
【发布时间】:2021-05-19 06:00:49
【问题描述】:

我有一个包含 XML 列的下表:

Id Label Details
1 Test1 <terms><destination><email>email11@foo.com</email><email>email12@foo.com</email></destination><content>blabla</content></terms>
2 Test2 <terms><destination><email>email21@foo.com</email><email>email22@foo.com</email></destination><content>blabla</content></terms>

我想要一个产生以下输出的查询:

Id Label Destination
1 Test1 email11@foo.com, email12@foo.com
2 Test2 email21@foo.com, email22@foo.com

关于如何将 XML 电子邮件节点值连接为相关列(Id 和 Label)的列的任何线索? 先谢谢了

【问题讨论】:

    标签: sql-server xml concatenation stuff


    【解决方案1】:

    请尝试以下解决方案。

    由于未提供 DDL 和样本数据总体, 假设 Details 列是 XML 数据类型。

    SQL

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, Label VARCHAR(20), Details XML);
    INSERT INTO @tbl (Label, Details) VALUES
    ('Test1',N'<terms><destination><email>email11@foo.com</email><email>email12@foo.com</email></destination><content>blabla</content></terms>'),
    ('Test2',N'<terms><destination><email>email21@foo.com</email><email>email22@foo.com</email></destination><content>blabla</content></terms>');
    -- DDL and sample data population, end
    
    SELECT ID, Label 
        , REPLACE(Details.query('data(/terms/destination/email/text())').value('.','VARCHAR(MAX)'), SPACE(1), ', ') AS Destination
    FROM @tbl;
    

    输出

    +----+-------+----------------------------------+
    | ID | Label |           Destination            |
    +----+-------+----------------------------------+
    |  1 | Test1 | email11@foo.com, email12@foo.com |
    |  2 | Test2 | email21@foo.com, email22@foo.com |
    +----+-------+----------------------------------+
    

    【讨论】:

      【解决方案2】:
      select ID, Label,
          stuff(
              details.query('for $step in /terms/destination/email/text() return concat(", ", string($step))')
              .value('.', 'nvarchar(max)'),
          1, 2, '')
      from @tbl;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-23
        • 2017-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多