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 :

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.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


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

 
  Feedback:

comments

1 Response to "How to import XML data in SQL Server"
  1. Mukesh Thapa said...
    September 23, 2010 at 11:17 PM
    This comment has been removed by the author.
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions