SQL Server is capable of reading XML and inserting it as you need. Here is an example of an XML file and insertion pulled from here:

XML:

<Products>
  <Product>
    <SKU>1</SKU>
    <Desc>Book</Desc>
  </Product>
  <Product>
    <SKU>2</SKU>
    <Desc>DVD</Desc>
  </Product>
  <Product>
    <SKU>3</SKU>
    <Desc>Video</Desc>
  </Product>
</Products>

Insert statement that is parsing the XML:

INSERT INTO Products (sku, product_desc) 
SELECT X.product.query('SKU').value('.', 'INT'),
       X.product.query('Desc').value('.', 'VARCHAR(30)')
FROM ( 
SELECT CAST(x AS XML)
FROM OPENROWSET(
     BULK 'C:\Products.xml',
     SINGLE_BLOB) AS T(x)
     ) AS T(x)
CROSS APPLY x.nodes('Products/Product') AS X(product);
Answer from Ocelot20 on Stack Overflow
Top answer
1 of 2
13

SQL Server is capable of reading XML and inserting it as you need. Here is an example of an XML file and insertion pulled from here:

XML:

<Products>
  <Product>
    <SKU>1</SKU>
    <Desc>Book</Desc>
  </Product>
  <Product>
    <SKU>2</SKU>
    <Desc>DVD</Desc>
  </Product>
  <Product>
    <SKU>3</SKU>
    <Desc>Video</Desc>
  </Product>
</Products>

Insert statement that is parsing the XML:

INSERT INTO Products (sku, product_desc) 
SELECT X.product.query('SKU').value('.', 'INT'),
       X.product.query('Desc').value('.', 'VARCHAR(30)')
FROM ( 
SELECT CAST(x AS XML)
FROM OPENROWSET(
     BULK 'C:\Products.xml',
     SINGLE_BLOB) AS T(x)
     ) AS T(x)
CROSS APPLY x.nodes('Products/Product') AS X(product);
2 of 2
6

I tried this and for 975 rows from a 1MB XML file, this took about 2.5 minutes to execute on a very fast PC.

I switched to using OpenXml in a multi-step process and process takes less than a second.

CREATE TABLE XMLwithOpenXML
(
    Id INT IDENTITY PRIMARY KEY,
    XMLData XML,
    LoadedDateTime DATETIME
)    

INSERT INTO XMLwithOpenXML(XMLData, LoadedDateTime)
SELECT CONVERT(XML, BulkColumn) AS BulkColumn, GETDATE() 
FROM OPENROWSET(BULK 'clients.xml', SINGLE_BLOB) AS x;



DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)    

SELECT @XML = XMLData FROM XMLwithOpenXML WHERE ID = '1' -- The row to process    

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML


INSERT INTO Clients
SELECT CustomerID, CustomerName
FROM OPENXML(@hDoc, 'Clients/Client')
WITH 
(
    CustomerID varchar 'ID',
    CustomerName varchar 'Name'
)


EXEC sp_xml_removedocument @hDoc
GO

I got this from here: http://www.mssqltips.com/sqlservertip/2899/importing-and-processing-data-from-xml-files-into-sql-server-tables/

Basically you load the XML into a table as a big blob of text, then you use OpenXml to process it.

🌐
Microsoft Learn
learn.microsoft.com › en-us › sql › relational-databases › import-export › examples-of-bulk-import-and-export-of-xml-documents-sql-server
Bulk import & export of XML documents - SQL Server | Microsoft Learn
June 21, 2023 - INSERT INTO T ( XmlCol ) SELECT x.BulkColumn FROM OPENROWSET( BULK 'C:\SampleFolder\SampleData3.txt', SINGLE_BLOB) AS x; By using SINGLE_BLOB in this case, you can avoid a mismatch between the encoding of the XML document (as specified by the XML encoding declaration) and the string codepage implied by the server.
Discussions

Bulk Insert XML document into SQL table. How? – SQLServerCentral Forums
Bulk Insert XML document into SQL table. How? Forum – Learn more on SQLServerCentral More on sqlservercentral.com
🌐 sqlservercentral.com
December 9, 2008
Bulk insert XML data into SQL Server - Stack Overflow
This option offers a higher performance ... of SQL Server to another using a data file. It does not prompt for each field. Use this option when you are transferring data that contains ANSI extended characters and you want to take advantage of the performance of native mode. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 12 Why do I get "XML parsing: line 2, character 0, incorrect document syntax" when Bulk Inserting in MS SQL ... More on stackoverflow.com
🌐 stackoverflow.com
February 15, 2010
Inserting huge amounts of XML data in relational tables – SQLServerCentral Forums
I have found that a much faster way of parsing large amounts xml for insertion into a table is to use XmlReader. XmlReader gives you very fast, forward only read access to an xml blob. As you read through the xml, create a csv file that you can then bulk load into sql server with bcp.exe (or ... More on sqlservercentral.com
🌐 sqlservercentral.com
September 22, 2007
c# - Bulk insert XML data into SQL Server database - Stack Overflow
I am working on backup and restore selective data from SQL Server. I am using the following solution: export multiple tables from mssql to xml and create a xml with the data I want. How can I cr... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
joemoceri.medium.com › bulk-insert-xml-into-sql-server-table-ca2653ab1806
Bulk insert XML into SQL Server table | by Joe Moceri | Medium
July 28, 2019 - DECLARE @xml TABLE (x XML) INSERT @xml SELECT x FROM OPENROWSET(BULK 'EmployeesData.xml', SINGLE_BLOB) AS T(x) INSERT INTO Employees SELECT result.LastName, result.FirstName, result.Title, result.TitleOfCourtesy, result.BirthDate, result.HireDate, result.[Address], result.City, result.Region, result.PostalCode, result.Country, result.HomePhone, result.Extension, result.Photo, result.Notes, result.ReportsTo, result.PhotoPath FROM @xml CROSS APPLY ( SELECT LastName = z.value('LastName[1]', 'nvarchar(20)'), FirstName = z.value('FirstName[1]', 'nvarchar(10)'), Title = z.value('Title[1]', 'nvarchar
🌐
GitHub
github.com › MicrosoftDocs › sql-docs › blob › live › docs › relational-databases › import-export › examples-of-bulk-import-and-export-of-xml-documents-sql-server.md
sql-docs/docs/relational-databases/import-export/examples-of-bulk-import-and-export-of-xml-documents-sql-server.md at live · MicrosoftDocs/sql-docs
INSERT INTO T ( XmlCol ) SELECT x.BulkColumn FROM OPENROWSET( BULK 'C:\SampleFolder\SampleData3.txt', SINGLE_BLOB) AS x; By using SINGLE_BLOB in this case, you can avoid a mismatch between the encoding of the XML document (as specified by the XML encoding declaration) and the string codepage implied by the server.
Author   MicrosoftDocs
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › bulk-insert-xml-document-into-sql-table-how
Bulk Insert XML document into SQL table. How? – SQLServerCentral Forums
December 9, 2008 - IF you get your "rowterminator" right you can probably use the BULK INSERT into a blob but in that case I would rather use the above snippet. ... That's not what I'm looking for. What I'm looking for is to transfer XML data into SQL table rowsets:
🌐
C# Corner
c-sharpcorner.com › article › bulk-insert-update-xml-data-into-sql-table
Bulk Insert, Update XML Data Into SQL Table
September 15, 2018 - When used wisely, it can provide useful extensions to SQL Server. Robert Sheldon, in the first part of a series, describes how to create an index a typed XML column in a table, and discusses when you should consider using an XML Datatype Part 1 Suppose the user is passing data from a function in XML format which contains some employee information having properties like TravelId, TravelCity etc. In below code, I am using temp table #Travel. XML contains a single record. Using SQL code insert this XML data into a temp table.
🌐
C# Corner
c-sharpcorner.com › article › how-to-insert-bulk-records-into-sql-server-using-xml-data-type
How To Insert Bulk Records Into SQL Server Using XML Data Type
March 10, 2018 - How many ways are there to insert bulk data into the database? ... Create user defined type in database and send your whole table to this type. SQL query can read every record and perform insert action to the database.
Find elsewhere
🌐
Microsoft Knowledge Base
mskb.pkisolutions.com › kb › 316005
How to import XML into SQL Server with the XML Bulk Load ...
Run the VBScript program C:\Insertcustomers.vbs to insert the three customer records into the Customer table. In SQL Query Analyzer, switch to the MyDatabase database, and then run this query: SELECT * FROM Customer Note that the three records created in the "Create the XML data source file" heading are now in the Customer table. ... Mapping an XML document to multiples tables by using a relationship specified in the XML schema file. Generating table schemas before bulk loading.
🌐
Microsoft Learn
learn.microsoft.com › en-us › sql › relational-databases › sqlxml-annotated-xsd-schemas-xpath-queries › bulk-load-xml › introduction-to-xml-bulk-load-sqlxml-4-0
Introduction to XML Bulk Load (SQLXML) - SQL Server | Microsoft Learn
March 3, 2023 - You can insert XML data into a SQL Server database by using an INSERT statement and the OPENXML function; however, the Bulk Load utility provides better performance when you need to insert large amounts of XML data.
Top answer
1 of 2
2

The basic syntax for using bcp is:

bcp <table_name> <direction> <file_name> <options> 

Where the arguments take the following values:

  • table_name is the fully qualified name of the table. For example, you might use inventory.dbo.fruits to insert records into the fruits table, owned by the database owner, in the inventory database.
  • direction indicates whether you want to import (“in” direction) or export (“out” direction) data.
  • file_name is the full path to the file. For example, you could import the file C:\fruit\inventory.txt.
  • options allow you to specify parameters for the bulk operation. For example, you can specify the maximum number of errors allowed with the –m option. You may also use the –x option to specify an XML file format. Consult Microsoft’s bcp documentation for a full list.

Will need more info to know what switches to use, but it should be somehting like

bcp database.dbo.MyTable in "C:\folder\xmlfile.xml" -c -T

-c Performs the operation using a character data type.
-T Specifies that the bcp utility connects to SQL Server with a trusted connection using integrated security.

Also here is Microsoft's bcp Utility which should help you with knowing what switches to use.

2 of 2
0

use -N switch if your file contains unicode characters.

-N : Performs the bulk-copy operation using the native (database) data types of the data for noncharacter data, and Unicode characters for character data. This option offers a higher performance alternative to the -w option, and is intended for transferring data from one instance of SQL Server to another using a data file. It does not prompt for each field. Use this option when you are transferring data that contains ANSI extended characters and you want to take advantage of the performance of native mode.

🌐
C# Corner
c-sharpcorner.com › blogs › bulk-insert-into-sql-database-using-xml-file1
Bulk insert into sql database using xml file
October 14, 2011 - It makes no difference other than limitation on the size of the document you wish to pass through Write the following code in button click event. string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("XML_Files/Employee.xml")); string strxml = XDocument.Load(Server.MapPath("XML_Files/Employee.xml")).ToString(); SqlConnection sqlconn = new SqlConnection(connStr); SqlCommand sqlcmd = new SqlCommand(); sqlcmd.Connection = sqlconn; sqlcmd.CommandType = CommandType.StoredProcedure; sqlcmd.CommandText = "xmlToEmp"; sqlcmd.Parameters.AddWithValue("@xmlstr", strxml); sqlconn.Open(); sqlcmd.ExecuteNonQuery(); sqlconn.Close();
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › inserting-huge-amounts-of-xml-data-in-relational-tables
Inserting huge amounts of XML data in relational tables – SQLServerCentral Forums
September 22, 2007 - XmlReader gives you very fast, forward only read access to an xml blob. As you read through the xml, create a csv file that you can then bulk load into sql server with bcp.exe (or BULK INSERT/DTS/SSIS etc).
🌐
Devart
devart.com › dbforge › sql › studio › bulk-insert-in-sql-server.html
Bulk Insert in SQL Server: Syntax, Examples and Best Practices
DECLARE @xml XML; SELECT @xml = BulkColumn FROM OPENROWSET(BULK 'C:\Data\input.xml', SINGLE_BLOB) AS data; These require parsing logic but give you flexibility over structure. ... They give you field-level control that raw BULK INSERT can't match.
🌐
MSSQLTips
mssqltips.com › home › simple way to import xml data into sql server with t-sql
Simple way to Import XML Data into SQL Server with T-SQL
February 25, 2022 - The first thing we are doing is a simple INSERT into our table CUSTOMERS_TABLE. The columns in the SELECT are pulled from the alias we created named MY_XML. We are querying each element of the Customer node. The FROM clause comes from using the OPENROWSET operation using the BULK option and the SINGLE_BLOB option to have the data returned from the XML file into a single column and row.
🌐
Microsoft Learn
learn.microsoft.com › en-us › sql › relational-databases › import-export › xml-format-files-sql-server
XML Format Files (SQL Server) - SQL Server | Microsoft Learn
July 15, 2025 - XML format files are only supported when SQL Server tools are installed together with SQL Server Native Client. You can use an XML format file with a bcp command, BULK INSERT statement, or INSERT ...
🌐
Stack Overflow
stackoverflow.com › questions › 27223232 › inserting-data-into-sql-server-table-from-a-bulk-xml
Inserting data into SQL SERVER table from a bulk #xml - Stack Overflow
0 Insert or Update rows Via XML in SQL Server (Bulk) 1 Bulk insert into SQL Server 2008 R2 from XML RAW data · 1 Load XML data into SQL Server, special XML structure · 0 Insertion into multiple tables in sql server via xml · 1 Insert XML nodes into a table in SQL Server ·
Top answer
1 of 2
2

SQL Server doesn't support fn::position() or preceding-sibling:: syntaxes. But you can use a hack involving << to get the position of each node.

So we calculate the position of each Column node, then push those values into the Value lookups

SELECT
  id         = x2.Row.value('@id', 'int'),
  Salutation = x2.Row.value('(Value[sql:column("ColIndex.Salutation")]/text())[1]', 'varchar(60)'),
  [Name]     = x2.Row.value('(Value[sql:column("ColIndex.Name"      )]/text())[1]', 'varchar(100)'),
  Birthday   = x2.Row.value('(Value[sql:column("ColIndex.Birthday"  )]/text())[1]', 'date'),
  [Filename] = x2.Row.value('(Value[sql:column("ColIndex.Filename"  )]/text())[1]', 'varchar(100)')

FROM @xml.nodes('/Root/Rowset/Columns') x1(Col)
CROSS APPLY (
    SELECT
       Salutation = x1.Col.value('let $c:= Column[@name="Salutation"][1] return count(Column[. << $c]) + 1', 'int'),
       [Name]     = x1.Col.value('let $c:= Column[@name="Name"]      [1] return count(Column[. << $c]) + 1', 'int'),
       Birthday   = x1.Col.value('let $c:= Column[@name="Birthday"]  [1] return count(Column[. << $c]) + 1', 'int'),
       [Filename] = x1.Col.value('let $c:= Column[@name="Filename"]  [1] return count(Column[. << $c]) + 1', 'int')
) ColIndex

CROSS APPLY @xml.nodes('/Root/Rows/Row') x2(Row);

db<>fiddle

2 of 2
1

If you want to keep your current approach of importing the file, you can, with the following changes:

set ansi_nulls on;
declare @xmlfile xml;

select @xmlfile = bulkcolumn
from  openrowset(bulk 'C:\Meta.xml', single_blob) x;

select 
       id           =      c.value('@id', 'int'),
       Salutation   =      c.value('(Value[count(/Root/Rowset/Columns/Column[@name="Salutation"]/preceding-sibling::*) + 1]/text())[1]', 'varchar(60)'),
       [Name]       =      c.value('(Value[count(/Root/Rowset/Columns/Column[@name="Name"]/preceding-sibling::*) + 1]/text())[1]', 'varchar(100)'),
       Birthday     =      c.value('(Value[count(/Root/Rowset/Columns/Column[@name="Birthday"]/preceding-sibling::*) + 1]/text())[1]', 'date'),
       [Filename]   =      c.value('(Value[count(/Root/Rowset/Columns/Column[@name="Filename"]/preceding-sibling::*) + 1]/text())[1]', 'varchar(100)')

into #Meta --

from @xmlfile.nodes('/Root/Rows/Row') as T(c);

set ansi_nulls off;

This finds the right <Value> position by looking up the <Column> of the given name and figuring out how many columns precede it. Not pretty, but effective.

If this is a one-off and/or you're certain of the column order, you can of course access the values directly.

       Birthday     =      c.value('(Value[8]/text())[1]', 'varchar(60)'),
🌐
Stack Overflow
stackoverflow.com › questions › 74687576 › getting-the-desired-view-result-of-xml-in-sql-server-bulk-insert-xml-into-table
Getting the desired view/result of XML in SQL Server (Bulk Insert XML into table) - Stack Overflow
DECLARE @xml xml SELECT @xml = C FROM OPENROWSET (BULK 'E:\Cell_Sense\CM_Input\my_xml.xml', SINGLE_BLOB) AS Cars(C) SELECT AID = xc.value('(parameter[@name="AID"]/@value)[1]', 'varchar(20)'), ALVL = xc.value('(parameter[@name="ALVL"]/@value)[1]', 'varchar(20)'), ANM = xc.value('(parameter[@name="ANM"]/@value)[1]', 'varchar(50)'), ASS = xc.value('(parameter[@name="ASS"]/@value)[1]', 'varchar(50)'), SHLDFLG = xc.value('(parameter[@name="SHLDFLG"]/@value)[1]', 'varchar(50)') FROM @xml.nodes('/bulkCmConfigDataFile/configData/class/object/class/object') AS XT(XC)
🌐
Stack Overflow
stackoverflow.com › questions › 54229484 › how-to-bulk-insert-rows-with-some-columns-of-xml-type-into-the-database
c# - How to bulk insert rows with some columns of xml type into the database? - Stack Overflow
The data type for ProcessData, MetaData and ResultData should be XmlDocument. ... I've managed to do this by serializing the XElement to string and setting the column to string in DataTable. I already had a model created by Linq to SQL, so I prepared a second model with string in place of XElement and bulk copied that.