My Blog List

hotinit.com. Powered by Blogger.

Search This Blog

Importing XML File to Sql Server Table

Tuesday, 26 June 2012

 Here is the example on how to import an xml file in the sql server installed machine to sql server table. Steps to do this 
1. Save the xml file to a location on your drive eg.C:\xmlfiles\Students.xml
2. Create Table Students
3. Import the xml using Openrowset bulk option  and select the values in xml using xpath and xquery
    and Do a Insert into using select
4. Results
STEP 1
The contents of the saved file will be
<Students>
  <Student>
    <Id>1</Id>
    <Name>Madhan</Name>
  </Student>
  <Student>
    <Id>2</Id>
    <Name>Karthi</Name>
  </Student>
  <Student>
    <Id>3</Id>
    <Name>Bata</Name>
  </Student>
</Students>
STEP 2
The syntax to create a table
CREATE TABLE TblStudents
(
 Id INT PRIMARY KEY,
 Name VARCHAR(50)
);
STEP 3
Query to select the values from xml and to extract

INSERT INTO TblStudents (Id , Name )
SELECT students.student.query('Id').value('.', 'INT') as Id,
       students.student.query('Name').value('.', 'VARCHAR(30)') as Name
FROM (
SELECT CAST(b AS XML)
FROM OPENROWSET(
     BULK 'C:\xmlfiles\Students.xml',
     SINGLE_BLOB) AS a(b)
     ) AS a(b)
CROSS APPLY b.nodes('Students/Student') AS students(student);

STEP 4

SELECT Id, Name FROM TblStudents;

/*
Results:
Id        Name
----------- -------------
1           Madhan
2           Karthi
3           Bata

*/






No comments:

Post a Comment

 

Blogger news

Blogroll

Most Reading

8.6/10