代码之家  ›  专栏  ›  技术社区  ›  Android Coder

如何在t-sql中汇总xml属性值?

  •  0
  • Android Coder  · 技术社区  · 3 年前

    我在MS-SQL表的数据字段中获得了以下xml数据。我想 选择每个表时,求和所有“RecordCount”属性的总值 一行我该怎么做呢?

        <BatchSummary BatchNumber="7" BatchType="SecOwnerTransfer">
          <InterfaceTable TableName="ASR.aps_transferevents" RecordCount="1438" />
          <InterfaceTable TableName="ASR.aps_transferowners" RecordCount="3462" />
          <InterfaceTable TableName="ASR.APS_DeleteTransferEvents" RecordCount="122" />
        </BatchSummary>
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   Yitzhak Khabinsky    3 年前

    请尝试以下解决方案。

    SQL

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xmldata XML);
    INSERT INTO @tbl (xmldata) VALUES
    (N'<BatchSummary BatchNumber="7" BatchType="SecOwnerTransfer">
          <InterfaceTable TableName="ASR.aps_transferevents" RecordCount="1438" />
          <InterfaceTable TableName="ASR.aps_transferowners" RecordCount="3462" />
          <InterfaceTable TableName="ASR.APS_DeleteTransferEvents" RecordCount="122" />
        </BatchSummary>'),
    (N'<BatchSummary BatchNumber="7" BatchType="SecOwnerTransfer">
          <InterfaceTable TableName="ASR.aps_transferevents" RecordCount="1" />
          <InterfaceTable TableName="ASR.aps_transferowners" RecordCount="3" />
          <InterfaceTable TableName="ASR.APS_DeleteTransferEvents" RecordCount="10" />
        </BatchSummary>');
    -- DDL and sample data population, end
    
    SELECT t.*
        , c.value('sum(InterfaceTable/@RecordCount)', 'INT') AS Result
    FROM @tbl AS t
        CROSS APPLY xmldata.nodes('/BatchSummary') AS t1(c);
    

    输出

    +----+--------+
    | ID | Result |
    +----+--------+
    |  1 |   5022 |
    |  2 |     14 |
    +----+--------+