<p>What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so:</p>

<pre><code>INSERT INTO some_table (column1, column2, column3)
SELECT
Rows.n.value('(@column1)[1]', 'varchar(20)'),
Rows.n.value('(@column2)[1]', 'nvarchar(100)'),
Rows.n.value('(@column3)[1]', 'int'),
FROM @xml.nodes('//Rows') Rows(n)
</code></pre>

<p>However I find that this is getting very slow for even moderate size xml data.</p>

[{'answer_id': 61246, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': "<p>I'm not sure what is the best method. I used OPENXML construction:</p>\n\n<pre><code>INSERT INTO Test\nSELECT Id, Data \nFROM OPENXML (@XmlDocument, '/Root/blah',2)\nWITH (Id   int         '@ID',\n      Data varchar(10) '@DATA')\n</code></pre>\n\n<p>To speed it up, you can create XML indices. You can set index specifically for <strong>value</strong> function performance optimization. Also you can use typed xml columns, which performs better.</p>\n"}, {'answer_id': 631578, 'author': 'DannykPowell', 'author_id': 67617, 'author_profile': 'https://Stackoverflow.com/users/67617', 'pm_score': 1, 'selected': False, 'text': '<p>This isn\'t an answer, more an addition to this question - I have just come across the same problem and I can give figures as edg asks for in the comment.</p>\n\n<p>My test has xml which results in 244 records being inserted - so 244 nodes.</p>\n\n<p>The code that I am rewriting takes on average 0.4 seconds to run.(10 tests run, spread from .56 secs to .344 secs) Performance is not the main reason the code is being rewritten, but the new code needs to perform as well or better. This old code loops the xml nodes, calling a sp to insert once per loop</p>\n\n<p>The new code is pretty much just a single sp; pass the xml in; shred it.</p>\n\n<p>Tests with the new code switched in show the new sp takes on average 3.7 seconds - almost 10 times slower.</p>\n\n<p>My query is in the form posted in this question;  </p>\n\n<pre><code>INSERT INTO some_table (column1, column2, column3)\nSELECT\nRows.n.value(\'(@column1)[1]\', \'varchar(20)\'),\nRows.n.value(\'(@column2)[1]\', \'nvarchar(100)\'),\nRows.n.value(\'(@column3)[1]\', \'int\'),\nFROM @xml.nodes(\'//Rows\') Rows(n)\n</code></pre>\n\n<p>The execution plan appears to show that for each column, sql server is doing a separate "Table Valued Function [XMLReader]" returning all 244 rows, joining all back up with Nested Loops(Inner Join). So In my case where I am shredding from/ inserting into about 30 columns, this appears to happen separately 30 times.</p>\n\n<p>I am going to have to dump this code, I don\'t think any optimisation is going to get over this method being inherently slow. I am going to try the sp_xml_preparedocument/OPENXML method and see if the performance is better for that. If anyone comes across this question from a web search (as I did) I would highly advise you to do some performance testing before using this type of shredding in SQL Server</p>\n'}, {'answer_id': 631621, 'author': 'si618', 'author_id': 44540, 'author_profile': 'https://Stackoverflow.com/users/44540', 'pm_score': 0, 'selected': False, 'text': '<p>There is an <a href="http://msdn.microsoft.com/en-us/library/ms171769.aspx" rel="nofollow noreferrer">XML Bulk load</a> COM object (<a href="http://msdn.microsoft.com/en-us/library/ms171878.aspx" rel="nofollow noreferrer">.NET Example</a>) </p>\n\n<p>From <a href="http://msdn.microsoft.com/en-us/library/ms171721.aspx" rel="nofollow noreferrer">MSDN</a>:</p>\n\n<blockquote>\n  <p>You can insert XML data into a SQL\n  Server database by using an INSERT\n  statement and the OPENXML function;\n  however, the Bulk Load utility\n  provides better performance when you\n  need to insert large amounts of XML\n  data.</p>\n</blockquote>\n'}, {'answer_id': 631854, 'author': 'Eddie Groves', 'author_id': 5769, 'author_profile': 'https://Stackoverflow.com/users/5769', 'pm_score': 0, 'selected': False, 'text': '<p>My current solution for large XML sets (> 500 nodes) is to use SQL Bulk Copy (System.Data.SqlClient.SqlBulkCopy) by using a DataSet to load the XML into memory and then pass the table to SqlBulkCopy (defining a XML schema helps).</p>\n\n<p>Obviously there a pitfalls such as needlessly using a DataSet and loading the whole document into memory first. I would like to go further in the future and implement my own IDataReader to bypass the DataSet method but currently the DataSet is "good enough" for the job. </p>\n\n<p>Basically I never found a solution to my original question regarding the slow performance for that type of XML shredding. It could be slow due to the typed xml queries being inherently slow or something to do with transactions and the the SQL Server log. I guess the typed xml functions were never designed for operating on non-trivial node sizes.</p>\n\n<p>XML Bulk Load: I tried this and it <em>was</em> fast but I had trouble getting the COM dll to work under 64bit environments and I generally try to avoid COM dlls that no longer appear to be supported.</p>\n\n<p>sp_xml_preparedocument/OPENXML: I never went down this road so would be interested to see how it performs.</p>\n'}, {'answer_id': 4671129, 'author': 'Dan', 'author_id': 572994, 'author_profile': 'https://Stackoverflow.com/users/572994', 'pm_score': 7, 'selected': True, 'text': '<p>Stumbled across this question whilst having a very similar problem, I\'d been running a query processing a 7.5MB XML file (~approx 10,000 nodes) for around 3.5~4 hours before finally giving up.</p>\n\n<p>However, after a little more research I found that having typed the XML using a schema and created an XML Index (I\'d bulk inserted into a table) the same query completed in ~ 0.04ms.</p>\n\n<p>How\'s that for a performance improvement!</p>\n\n<p>Code to create a schema:</p>\n\n<pre><code>IF EXISTS ( SELECT * FROM sys.xml_schema_collections where [name] = \'MyXmlSchema\')\nDROP XML SCHEMA COLLECTION [MyXmlSchema]\nGO\n\nDECLARE @MySchema XML\nSET @MySchema = \n(\n    SELECT * FROM OPENROWSET\n    (\n        BULK \'C:\\Path\\To\\Schema\\MySchema.xsd\', SINGLE_CLOB \n    ) AS xmlData\n)\n\nCREATE XML SCHEMA COLLECTION [MyXmlSchema] AS @MySchema \nGO\n</code></pre>\n\n<p>Code to create the table with a typed XML column:</p>\n\n<pre><code>CREATE TABLE [dbo].[XmlFiles] (\n    [Id] [uniqueidentifier] NOT NULL,\n\n    -- Data from CV element \n    [Data] xml(CONTENT dbo.[MyXmlSchema]) NOT NULL,\n\nCONSTRAINT [PK_XmlFiles] PRIMARY KEY NONCLUSTERED \n(\n    [Id] ASC\n)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]\n) ON [PRIMARY]\n</code></pre>\n\n<p>Code to create Index</p>\n\n<pre><code>CREATE PRIMARY XML INDEX PXML_Data\nON [dbo].[XmlFiles] (Data)\n</code></pre>\n\n<p>There are a few things to bear in mind though. SQL Server\'s implementation of Schema doesn\'t support xsd:include. This means that if you have a schema which references other schema, you\'ll have to copy all of these into a single schema and add that.</p>\n\n<p>Also I would get an error:</p>\n\n<pre><code>XQuery [dbo.XmlFiles.Data.value()]: Cannot implicitly atomize or apply \'fn:data()\' to complex content elements, found type \'xs:anyType\' within inferred type \'element({http://www.mynamespace.fake/schemas}:SequenceNumber,xs:anyType) ?\'.\n</code></pre>\n\n<p>if I tried to navigate above the node I had selected with the nodes function. E.g.</p>\n\n<pre><code>SELECT\n    ,C.value(\'CVElementId[1]\', \'INT\') AS [CVElementId]\n    ,C.value(\'../SequenceNumber[1]\', \'INT\') AS [Level]\nFROM \n    [dbo].[XmlFiles]\nCROSS APPLY\n    [Data].nodes(\'/CVSet/Level/CVElement\') AS T(C)\n</code></pre>\n\n<p>Found that the best way to handle this was to use the OUTER APPLY to in effect perform an "outer join" on the XML.</p>\n\n<pre><code>SELECT\n    ,C.value(\'CVElementId[1]\', \'INT\') AS [CVElementId]\n    ,B.value(\'SequenceNumber[1]\', \'INT\') AS [Level]\nFROM \n    [dbo].[XmlFiles]\nCROSS APPLY\n    [Data].nodes(\'/CVSet/Level\') AS T(B)\nOUTER APPLY\n    B.nodes (\'CVElement\') AS S(C)\n</code></pre>\n\n<p>Hope that that helps someone as that\'s pretty much been my day.</p>\n'}, {'answer_id': 6405333, 'author': 'Tao', 'author_id': 74296, 'author_profile': 'https://Stackoverflow.com/users/74296', 'pm_score': 2, 'selected': False, 'text': '<p>I wouldn\'t claim this is the "best" solution, but I\'ve written a generic SQL CLR procedure for this exact purpose - it takes a "tabular" Xml structure (such as that returned by FOR XML RAW) and outputs a resultset.</p>\n\n<p>It does not require any customization / knowledge of the structure of the "table" in the Xml, and turns out to be extremely fast / efficient (although this wasn\'t a design goal). I just shredded a 25MB (untyped) xml variable in under 20 seconds, returning 25,000 rows of a pretty wide table.</p>\n\n<p>Hope this helps someone:\n<a href="http://architectshack.com/ClrXmlShredder.ashx" rel="nofollow">http://architectshack.com/ClrXmlShredder.ashx</a></p>\n'}, {'answer_id': 9794641, 'author': 'edhubbell', 'author_id': 1054938, 'author_profile': 'https://Stackoverflow.com/users/1054938', 'pm_score': 2, 'selected': False, 'text': "<p>We had a similar issue here.  Our DBA (SP, you the man) took a look at my code, made a little tweak to the syntax, and we got the speed we had been expecting.  It was unusual because my select from XML was plenty fast, but the insert was way slow.  So try this syntax instead:</p>\n\n<pre><code>INSERT INTO some_table (column1, column2, column3)\n    SELECT \n        Rows.n.value(N'(@column1/text())[1]', 'varchar(20)'), \n        Rows.n.value(N'(@column2/text())[1]', 'nvarchar(100)'), \n        Rows.n.value(N'(@column3/text())[1]', 'int')\n    FROM @xml.nodes('//Rows') Rows(n) \n</code></pre>\n\n<p>So specifying the text() parameter really seems to make a difference in performance.  Took our insert of 2K rows from 'I must have written that wrong - let me stop it' to about 3 seconds.  Which was 2x faster than the raw insert statements we had been running through the connection.</p>\n"}, {'answer_id': 18264248, 'author': 'jccprj', 'author_id': 2687849, 'author_profile': 'https://Stackoverflow.com/users/2687849', 'pm_score': 3, 'selected': False, 'text': '<p>in my case i\'m running SQL 2005 SP2 (9.0).</p>\n\n<p>The only thing that helped was adding OPTION ( OPTIMIZE FOR ( @your_xml_var = NULL ) ).\nExplanation is on the link below.</p>\n\n<p>Example:</p>\n\n<pre><code>INSERT INTO @tbl (Tbl_ID, Name, Value, ParamData)\nSELECT     1,\n    tbl.cols.value(\'name[1]\', \'nvarchar(255)\'),\n    tbl.cols.value(\'value[1]\', \'nvarchar(255)\'),\n    tbl.cols.query(\'./paramdata[1]\')\nFROM @xml.nodes(\'//root\') as tbl(cols) OPTION ( OPTIMIZE FOR ( @xml = NULL ) )\n</code></pre>\n\n<p><a href="https://connect.microsoft.com/SQLServer/feedback/details/562092/an-insert-statement-using-xml-nodes-is-very-very-very-slow-in-sql2008-sp1" rel="noreferrer">https://connect.microsoft.com/SQLServer/feedback/details/562092/an-insert-statement-using-xml-nodes-is-very-very-very-slow-in-sql2008-sp1</a></p>\n'}]
['https://Stackoverflow.com/questions/61233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5769/']