如何在Oracle中“打开”XML数据

时间:2009-10-21 18:49:53

标签: sql sql-server xml oracle plsql

以下是我想在PL / SQL中重写的一些TSQL的示例。

DECLARE @xml XML

SET @xml = '<theRange>
    <theRow><First>Bob</First><Last>Smith</Last><Age>30</Age></theRow>
    <theRow><First>Sue</First><Last>Jones</Last><Age>34</Age></theRow>
    <theRow><First>John</First><Last>Bates</Last><Age>40</Age></theRow>
</theRange>'

;WITH OpenedXML AS (
    SELECT  r.value('First[1]','varchar(50)') AS First,
        r.value('Last[1]','varchar(50)') AS Last,
        r.value('Age[1]','int') AS Age
    FROM @xml.nodes('//theRange/theRow') AS Row(r)
)
SELECT * 
FROM OpenedXML
WHERE Age BETWEEN 30 AND 35

任何人都可以在这里给我一些指导。

1 个答案:

答案 0 :(得分:3)

本SO中描述了几种方法:

Oracle Pl/SQL: Loop through XMLTYPE nodes

更新:它非常简单,因为两种方法都是纯SQL(您可以从PL / SQL或与数据库交互的任何工具调用此SQL):

SQL> WITH openedXml AS (
  2  SELECT extractvalue(column_value, '/theRow/First') FIRST,
  3         extractvalue(column_value, '/theRow/Last') LAST,
  4         to_number(extractvalue(column_value, '/theRow/Age')) Age
  5    FROM TABLE(XMLSequence(XMLTYPE('<theRange>
  6      <theRow><First>Bob</First><Last>Smith</Last><Age>30</Age></theRow>
  7      <theRow><First>Sue</First><Last>Jones</Last><Age>34</Age></theRow>
  8      <theRow><First>John</First><Last>Bates</Last><Age>40</Age></theRow>
  9  </theRange>').extract('/theRange/theRow')))
 10  )
 11  SELECT *
 12    FROM openedxml
 13   WHERE age BETWEEN 30 AND 35;

FIRST     LAST       AGE
--------- -------- -----
Bob       Smith       30
Sue       Jones       34