Need to create one generic stored procedure which will take table name as input parameter and create xml file with below format. Xml file name should be table name.
<XML>
<TABLENAME></TABLENAME>
<RECORDS>
<RECORD>
<COLNAME>AAA</COLNAME>
<COLNAME>AAA</COLNAME>
<RECORD>
<RECORD>
<COLNAME>AAA</COLNAME>
<COLNAME>AAA</COLNAME>
<RECORD>
<RECORD>
<COLNAME>AAA</COLNAME>
<COLNAME>AAA</COLNAME>
<RECORD>
<RECORD>
<COLNAME>AAA</COLNAME>
<COLNAME>AAA</COLNAME>
<RECORD>
<RECORD>
<COLNAME>AAA</COLNAME>
<COLNAME>AAA</COLNAME>
<RECORD>
</RECORDS>
</XML>
<TABLENAME> = actual table name(case should be same as in database)
<COLNAME> = actual column names from table(case should be same as in database)
Keep other tags as it is. Repeat <RECORD> tag for each row retrieved.
Oracle has a built-in function to get the contents of a table as XML:
You can add your own tags around that; could be done as a query but since you want a stored procedure:
So this has the structure you want (well, I think, but see below), but has
ROWSET
andROW
instead ofRECORDS
andRECORD
. That might not matter, it depends whether you're developing the format for this interface still. If it does matter then you can apply a further step to rename those nodes, or - more helpfully - use thedbms_xmlgen
proceduressetrowsettag
andsetrowtag
, which is simple in your procedure (and demonstrated below).I'm assuming what you showed as
<TABLENAME></TABLENAME>
was a mistake, and you want the records within that tag. If not, and you really do want that for some reason, change the query in the function to:You can then write that out to a file any way you normally would; if you're calling from SQL*Plus etc. you could select and spool, or if you don't want it returned at all you could add
UTL_FILE
directive to write the file from within the procedure, but that would have to be to a directory object on the DB server, which might not be convenient.Mostly for my own benefit as I don't do a lot with XML:
When run with
exec table_to_xml_file('T42')
, this produces a file calledT42.xml
in the server directory pointed to by the<directory>
directory object, which contains:Incidentally, I've put double-quotes around the table name in the select inside the
dbms_xmlgen.getxmltype
call. That's to meet the 'case should be same as in database' requirement for the table name; it has to be passed to the procedure in the correct case or it will error. That's simpler than trying to correct the case within the procedure somehow, which would be awkward, or impossible if you had two tables with the same name apart from the case. The columns names will be in the correct case anyway.