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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s