September 14, 2008

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 :

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

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"?>
<Customer ID="1">

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
) AS ImportXML (Disc)

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

About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

1 comment:

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