将此XML切成名称/值对

时间:2019-09-16 18:09:45

标签: sql-server xml

我在SQL Server中有一个需要粉碎的XML字段。数据看起来像这样。

<tags>
  <tags name="CLAIM_VIEW_ATTYFILENO" value="04-01883" order="0" />
  <tags name="_TODAY" value="February 14, 2019" order="12" />
  <tags name="CLAIM_VIEW_ATTYFILENO" value="04-01883" order="22" />
  <tags name="CLAIM_VIEW_CURRENTBALANCE" value="$7,484.34" order="-1" />
  <tags name="@NN_SIFAMT" value="$2,993.74" order="-1" />
  <tags name="@SETTLEMENT_DATE" value="April 30th, 2019" order="24" />
</tags>

此查询仅返回NULL:

SELECT TAGS.node.value('@NN_SIFAMT[1]','VARCHAR(50)') AS FILENO
FROM @data.nodes('/tags') AS TAGS(NODE)

我只需要返回值即可。

1 个答案:

答案 0 :(得分:0)

这是如何检索大多数值。因为XML在表列中,所以需要CROSS APPLY或OUTER APPLY。还有一个不同的XPath表达式。

  

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, xml_data XML);
INSERT INTO @tbl (xml_data)
VALUES
(N'<tags>
  <tags name="CLAIM_VIEW_ATTYFILENO" value="04-01883" order="0" />
  <tags name="_TODAY" value="February 14, 2019" order="12" />
  <tags name="CLAIM_VIEW_ATTYFILENO" value="04-01883" order="22" />
  <tags name="CLAIM_VIEW_CURRENTBALANCE" value="$7,484.34" order="-1" />
  <tags name="@NN_SIFAMT" value="$2,993.74" order="-1" />
  <tags name="@SETTLEMENT_DATE" value="April 30th, 2019" order="24" />
</tags>');
-- DDL and sample data population, end

SELECT ID
      , col.value('@name','VARCHAR(50)') AS col_name
      , col.value('@value','VARCHAR(50)') AS col_value
FROM @tbl tbl
    CROSS APPLY tbl.[xml_data].nodes('/tags/tags') AS tab(col);
  

输出:

+----+---------------------------+-------------------+
| ID |         col_name          |     col_value     |
+----+---------------------------+-------------------+
|  1 | CLAIM_VIEW_ATTYFILENO     | 04-01883          |
|  1 | _TODAY                    | February 14, 2019 |
|  1 | CLAIM_VIEW_ATTYFILENO     | 04-01883          |
|  1 | CLAIM_VIEW_CURRENTBALANCE | $7,484.34         |
|  1 | @NN_SIFAMT                | $2,993.74         |
|  1 | @SETTLEMENT_DATE          | April 30th, 2019  |
+----+---------------------------+-------------------+