We have all been creating SQL queries with parameters, maybe in different software like SQL Server, PL/SQL, DB2, etc.
Today, we are going to see how to handle XML Data in a SQL Query. I am going to use PL/SQL for it as I have that handy but I am pretty sure it can be done in SQL Server as well, obviously with a different format.
So let's begin.
Our XML format is as below,
- <parms>
- <parm>
- <FIRSTNAME>Vipul</FIRSTNAME>
- <LASTNAME>Malhotra</LASTNAME>
- <AGE>25</AGE>
- <GENDER>M</GENDER>
- </parm>
- <parm>
- <FIRSTNAME>Gaurav</FIRSTNAME>
- <LASTNAME>Malhotra</LASTNAME>
- <AGE>33</AGE>
- <GENDER>M</GENDER>
- </parm>
- </parms>
Now, let's start writing the query in the below steps.
Step 1
First we need to make sure that the text above is considered as XML and nothing else. We achieve this as:
- WITH t as (select XMLTYPE('
- <parms>
- <parm>
- <FIRSTNAME>Vipul</FIRSTNAME>
- <LASTNAME>Malhotra</LASTNAME>
- <AGE>25</AGE>
- <GENDER>M</GENDER>
- </parm>
- <parm>
- <FIRSTNAME>Gaurav</FIRSTNAME>
- <LASTNAME>Malhotra</LASTNAME>
- <AGE>33</AGE>
- <GENDER>M</GENDER>
- </parm>
- </parms>') as xml from dual)
Please notice that we have used it inside the "
WITH t as" only because we want to further use the xml data with Alias "t". For PL/Sql the "dual" is an inbuild function that you can read about more from the web.
Step 2
Now, we have to select the data from the Alias table "t" as described above and read the data from each node by reading though it. In order to do that we do mentioned the starting of the node. This is done as:
- select x.age,x.firstname,x.lastname,x.gender
- from t
- ,XMLTABLE('/parms/parm'
- PASSING t.xml
- COLUMNS age NUMBER PATH '/parm/AGE'
- , firstname VARCHAR2(50) PATH '/parm/FIRSTNAME'
- ,lastname VARCHAR(50) PATH '/parm/LASTNAME'
- ,gender CHAR(1) PATH '/parm/GENDER'
- ) x
-
-
In the sql above, we have mentioned the base of the node by the line and then we padded the earlier declared table "t" and read further nodes from it by iterating through the nodes like "
/parm/AGE" for age , '
/parm/FIRSTNAME' for FirstName, '
/parm/LASTNAME' for LastName and '
/parm/GENDER' for Gender.
The final code comes out to be as below,
- WITH t as (select XMLTYPE('
- <parms>
- <parm>
- <FIRSTNAME>Vipul</FIRSTNAME>
- <LASTNAME>Malhotra</LASTNAME>
- <AGE>25</AGE>
- <GENDER>M</GENDER>
- </parm>
- <parm>
- <FIRSTNAME>Gaurav</FIRSTNAME>
- <LASTNAME>Malhotra</LASTNAME>
- <AGE>33</AGE>
- <GENDER>M</GENDER>
- </parm>
- </parms>') as xml from dual)
-
- select x.age,x.firstname,x.lastname,x.gender
- from t
- ,XMLTABLE('/parms/parm'
- PASSING t.xml
- COLUMNS age NUMBER PATH '/parm/AGE'
- , firstname VARCHAR2(50) PATH '/parm/FIRSTNAME'
- ,lastname VARCHAR(50) PATH '/parm/LASTNAME'
- ,gender CHAR(1) PATH '/parm/GENDER'
- ) x
The output generated by the above query is as below,