Reading simple XML in SQL

SQL provides many in built functions which you can use to extract the data from XML, in this article we will read the data from XML using OPENXML method.

Steps involved in reading XML document are:

1) Declare one variable to hold the XML of XML data type.

2) Assign XML to variable.

3) Prepared XML document using  “sp_xml_preparedocument”  system stored procedure.

4) Use OPENXML and pass the xml document object prepared using step 3.

Example:

DECLARE @XML AS XML, @hDoc AS INT

SELECT @XML = '<Employees>
<Employee_Details>
<EmployeeID>1</EmployeeID><EmployeeName>ABC</EmployeeName>
<Contact><Address>Address of ABC</Address><CellNo>9876543210</CellNo></Contact>
</Employee_Details>
<Employee_Details>
<EmployeeID>2</EmployeeID><EmployeeName>PQR</EmployeeName>
<Contact><Address>Address of PQR</Address><CellNo>9876543211</CellNo></Contact>
</Employee_Details>
</Employees>'

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

SELECT *
FROM OPENXML(@hDoc, 'Employees/Employee_Details')
WITH 
(
EmployeeID Int 'EmployeeID',
EmployeeName [varchar](100) 'EmployeeName',
Address [varchar](200) 'Contact/Address',
CellNo [varchar](50) 'Contact/CellNo'
)

Output

XML
Advertisements

#xml-reading