【问题标题】:How to parse XML with other fields into multiple lines in SQL?如何在 SQL 中将带有其他字段的 XML 解析为多行?
【发布时间】:2019-04-17 08:14:52
【问题描述】:

我有一个包含数据字段的表格。其中一个字段是 XML 类型的。存储的 XML 至少有一个节点,其中包含我需要提取的子元素。

示例表格行:

Id  UserId  Date        XML
1   1001    2019-02-13  *

*XML =

<root>
    <action>
        <type>1</type>
        <res>0</res>
    </action>
    <action>
        <type>1</type>
        <res>10</res>
    </action>
    <action>
        <type>2</type>
        <res>-5</res>
    </action>
</root>

我知道如何使用 XML.value 获取单个值以及如何解析单独表中的所有节点。我只是不知道如何将两者结合成我需要的结果。

预期结果:

Id  UserId  Date        Type    Res
1   1001    2019-02-13  1        0
1   1001    2019-02-13  1       10
1   1001    2019-02-13  2       -5

【问题讨论】:

    标签: sql sql-server xml


    【解决方案1】:

    CROSS APPLY on nodes()是你的朋友:

    DECLARE @t TABLE(Id INT, UserId INT, [Date] DATETIME, [XML] XML);
    INSERT @t VALUES (1, 1001, '2019-02-13', N'
    <root>
        <action>
            <type>1</type>
            <res>0</res>
        </action>
        <action>
            <type>1</type>
            <res>10</res>
        </action>
        <action>
            <type>2</type>
            <res>-5</res>
        </action>
    </root>');
    
    SELECT 
        Id, 
        UserId, 
        [Date], 
        [Type] = [action].value('type[1]', 'int'),
        [Res] = [action].value('res[1]', 'int')
    FROM @t 
    CROSS APPLY [XML].nodes('/root/action') actions([action]);
    

    结果:

    +----+--------+-------------------------+------+-----+
    | Id | UserId |          Date           | Type | Res |
    +----+--------+-------------------------+------+-----+
    |  1 |   1001 | 2019-02-13 00:00:00.000 |    1 |   0 |
    |  1 |   1001 | 2019-02-13 00:00:00.000 |    1 |  10 |
    |  1 |   1001 | 2019-02-13 00:00:00.000 |    2 |  -5 |
    +----+--------+-------------------------+------+-----+
    

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多