Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT XML into SQL Server 2008 database

Hello I'm trying to insert some XML data into a table on SQL Server 2008. However I keep getting thrown this error;

XML parsing: line 1, character 39, unable to switch the encoding

The database column filemeta uses the XML datatype, and I've switch the encoding to UTF-16 which I believe is necessary for adding XML data.

INSERT INTO testfiles   (filename, filemeta)  VALUES    ('test.mp3', '<?xml version="1.0" encoding="utf-16" standalone="yes"?><!--This is a test XML file--><filemeta filetype="Audio"><Comments /><AlbumTitle /><TrackNumber /><ArtistName /><Year /><Genre /><TrackTitle /></filemeta>'); 

Help, I'm stuck.

NB: I created the XML with XMLTextWriter.

like image 252
wonea Avatar asked Sep 02 '10 15:09

wonea


People also ask

How insert bulk data in SQL Server using XML?

When you bulk import XML data from a file that contains an encoding declaration that you want to apply, specify the SINGLE_BLOB option in the OPENROWSET(BULK...) clause. The SINGLE_BLOB option ensures that the XML parser in SQL Server imports the data according to the encoding scheme specified in the XML declaration.

Can we store XML in SQL?

In SQL Server, you usually store XML data in a column configured with the xml data type. The data type supports several methods that let you query and modify individual elements, attributes, and their values directly within the XML instance, rather than having to work with that instance as a whole.

Can SQL read XML?

Now as I said before, XML data stored in a column of data type XML can be processed either by using XML functions available in SQL Server or by using the sp_xml_preparedocument stored procedure along with the OPENXML function.


1 Answers

Yes, there are issues when you try to insert XML into SQL Server 2008 and the XML contains an encoding instruction line.

I typically get around using the CONVERT function which allows me to instruct SQL Server to skip those instructions - use something like this:

INSERT INTO testfiles   (filename, filemeta)  VALUES    ('test.mp3', CONVERT(XML, N'<?xml version="1.0" encoding="utf-16" standalone="yes"?>......', 2)); 

It has definitely helped me get various encoded XML stuff into SQL Server.

See the MSDN docs on CAST and CONVERT - a bit down the page there's a number of styles you can use for CONVERT with XML and some explanations about them.

like image 128
marc_s Avatar answered Sep 20 '22 07:09

marc_s