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.
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,
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>
Step 1
First we need to make sure that the text above is considered as XML and nothing else. We achieve this as:
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)
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:
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
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)
- -- END OF TEST DATA
- 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


Join the conversation! Your thoughts help the community grow.