Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to save XML data to SQL Server?

Is there a direct route that is pretty straight forward? (i.e. can SQL Server read XML)

Or, is it best to parse the XML and just transfer it in the usual way via ADO.Net either as individual rows or perhaps a batch update?

I realize there may be solutions that involve large complex stored procs--while I'm not entirely opposed to this, I tend to prefer to have most of my business logic in the C# code. I have seen a solution using SQLXMLBulkLoad, but it seemed to require fairly complex SQL code.

For reference, I'll be working with about 100 rows at a time with about 50 small pieces of data for each (strings and ints). This will eventually become a daily batch job.

Any code snippets you can provide would be very much appreciated.

like image 747
alchemical Avatar asked Apr 01 '09 04:04

alchemical


2 Answers

SQL Server 2005 and up have a datatype called "XML" which you can store XML in - untyped or typed with a XSD schema.

You can basically fill columns of type XML from an XML literal string, so you can easily just use a normal INSERT statement and fill the XML contents into that field.

Marc

like image 133
marc_s Avatar answered Nov 16 '22 02:11

marc_s


You can use the function OPENXML and stored procedure sp_xml_preparedocument to easily convert your XML into rowsets.

like image 29
coder Avatar answered Nov 16 '22 02:11

coder