How to import XML data in SQL Server

In order to import XML data in SQL Server, you can use the BULK keyword with OPENROWSET

Let us explore how to import XML data with an example.

Step 1: Create an independent sample table in the Northwind database or any db of your choice :

USE NORTHWIND
CREATE TABLE CustomerDiscount (ID int NOT NULL, Discount xml)
GO

Step 2: Now create a XML file and save it on your disk. We will call the file 'sample.xml' and save it in C:\

<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<Customer ID="1">
<Discount>20</Discount>
</Customer>
</Customers>

Step 3: Let us now import the xml data from C:\sample.xml into our newly created table 'CustomerDiscount'

INSERT INTO CustomerDiscount(ID, Discount)
SELECT 1, Disc
FROM
(
SELECT * FROM OPENROWSET(BULK 'c:\sample.xml',SINGLE_BLOB) as Disc
) AS ImportXML (Disc)

Note: Do not forget to specify the UTF-8 encoding scheme in the XML file.


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

1 comment:

Mukesh Thapa said...
This comment has been removed by the author.