Frage

I have an XML stored in XMLTYPE column named as xml_file in a table named as XML_TABLE. I am using Oracle 11g r2.

<ROWSET> 
 <DEPARTMENT>
  <DEPARTMENT_ID>DEP22681352268280797</DEPARTMENT_ID>
  <DEPARTMENT_NAME>myDEPARTMENT</DEPARTMENT_NAME>
  <SECTIONS_ID>6390135666643567</SECTIONS_ID>
  <SECTIONS_NAME>mySection</SECTIONS_NAME>
 </DEPARTMENT>
 <DEPARTMENT>
  <DEPARTMENT_ID>DEP255555555550797</DEPARTMENT_ID>
  <DEPARTMENT_NAME>myDEPARTMENT2</DEPARTMENT_NAME>
  <SECTIONS_ID>63901667779243567</SECTIONS_ID>
  <SECTIONS_NAME>mySection2</SECTIONS_NAME>
 </DEPARTMENT>
</ROWSET>

I want to insert these values into two tables that are departments and and sections.How am going to implement this in PL/SQL. I have tried using extract function but i just read it that it is no more recommended, therefore seeking help. Moreover, i don't know how am i going to iterate the xml values..cursor...??

War es hilfreich?

Lösung

Use XQuery to split the XML document into chunks of interesting data. Represent those chunks with XMLTable to get something you can work with in SQL.

Here is a rough stab at a solution for your case (obviously it has to be rough, you haven't posted table structures, but I'm assuming SECTIONS has a foreign key to DEPARTMENTS). You should read the docs to find out more.

insert all
   into departments
       values (dept_id, dept_name)
   into sections
       values (dept_id, sect_id, sect_name)
select dept.id as dept_id
      , dept_name as dept_name
      , sect.id as sect_id
      , sect.name as sect_name
from your_table
     , xmltable('/ROWSET/DEPARTMENT'  
               passing your_table.xml_col
               columns 
                  "ID"  varchar2(30) path 'DEPARTMENT_ID'
                  , "NAME"  varchar2(30) path 'DEPARTMENT_NAME'
              ) dept
     , xmltable('/ROWSET/SECTION'  
               passing your_table.xml_col
               columns 
                  "ID"  varchar2(30) path 'SECTION_ID'
                  , "NAME"  varchar2(30) path 'SECTION_NAME'
              ) sect

Incidentally, the repetition of DEPARTMENT sucks. XML is a pain in the neck to work with but at least it supports hierarchical data structures. If you're not going to use that to avoid duplication you might as well be using CSVs. Anyway, as the posted XML doesn't contain any actual duplication solving its failings is left as an exercise for the reader.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top