Try this:

DECLARE @input XML = '<dataset> 
 <metadata>
  <item name="NAME_LAST" type="xs:string" length="62" /> 
  <item name="NAME_FIRST" type="xs:string" length="62" /> 
  <item name="NAME_MIDDLE" type="xs:string" length="32" />
 </metadata>
<data>
<row>
 <value>SMITH</value> 
 <value>MARY</value> 
 <value>N</value> 
</row>
<row>
 <value>SMITH2</value> 
 <value>MARY2</value> 
 <value>N2</value> 
</row>
</data>
</dataset>'

INSERT INTO dbo.YourTable(ColName, ColFirstName, ColOther)
   SELECT
      Name = XCol.value('(value)[1]','varchar(25)'),
      FirstName = XCol.value('(value)[2]','varchar(25)'),
      OtherValue = XCol.value('(value)[3]','varchar(25)')
   FROM 
      @input.nodes('/dataset/data/row') AS XTbl(XCol)
Answer from marc_s on Stack Overflow
Top answer
1 of 2
33

Try this:

DECLARE @input XML = '<dataset> 
 <metadata>
  <item name="NAME_LAST" type="xs:string" length="62" /> 
  <item name="NAME_FIRST" type="xs:string" length="62" /> 
  <item name="NAME_MIDDLE" type="xs:string" length="32" />
 </metadata>
<data>
<row>
 <value>SMITH</value> 
 <value>MARY</value> 
 <value>N</value> 
</row>
<row>
 <value>SMITH2</value> 
 <value>MARY2</value> 
 <value>N2</value> 
</row>
</data>
</dataset>'

INSERT INTO dbo.YourTable(ColName, ColFirstName, ColOther)
   SELECT
      Name = XCol.value('(value)[1]','varchar(25)'),
      FirstName = XCol.value('(value)[2]','varchar(25)'),
      OtherValue = XCol.value('(value)[3]','varchar(25)')
   FROM 
      @input.nodes('/dataset/data/row') AS XTbl(XCol)
2 of 2
9
Insert XML Data into sql Server table

Declare @retValue1 varchar(50);
Declare @XmlStr XML;
SET @XmlStr='<Customers>
 <customer>
    <ID>111589</ID>
    <FirstName>name1</FirstName>
    <LastName>Lname1</LastName>
    <Company>ABC</Company>
  </customer>
  <customer>
    <ID>12345</ID>
    <FirstName>name2</FirstName>
    <LastName>Lname2</LastName>
    <Company>ABC</Company>
  </customer>
  <customer>
    <ID>14567</ID>
    <FirstName>name3</FirstName>
    <LastName>Lname3</LastName>
    <Company>DEF</Company>
  </customer>
</Customers>';

@retValue='Failed';
 
INSERT INTO  test_xmlinsert
SELECT
COALESCE([Table].[Column].value('ID[1]', 'int'),0) as 'ID',
[Table].[Column].value('FirstName [1]', 'varchar(50)') as ' FirstName ',
[Table].[Column].value(' LastName[1]', 'varchar(50)') as ' LastName',
[Table].[Column].value(' Company [1]', 'varchar(50)') as ' Company'
 FROM @XmlStr.nodes('/ Customers / customer') as Table
IF(@@ROWCOUNT > 0 )
  SET @retValue='SUCCESS';
๐ŸŒ
SQLServerCentral
sqlservercentral.com โ€บ forums โ€บ topic โ€บ importing-an-xml-file-into-a-sql-table
Importing an XML file into a sql table โ€“ SQLServerCentral Forums
February 17, 2019 - --------------------------------------- ... is what i am trying to achieve but as im new to XML its hardd putting this into words. ... INSERT INTO XMLwithOpenXML(XMLData, LoadedDateTime) SELECT CONVERT(XML, BulkColumn) AS BulkColumn, GETDATE() FROM OPENROWSET(BULK 'C:\Scripts\ice...
Discussions

sql server - Insert XML File into specific sql table - Database Administrators Stack Exchange
I have the following xml document 12 123 ุงู„ู‡ุฏู More on dba.stackexchange.com
๐ŸŒ dba.stackexchange.com
how to insert the xml data to sql server using c#? - Stack Overflow
I am beginner to the C#, I need to insert my XML file to SQL table pro-grammatically XML file have five nodes called root, name, subject, sno and queries, I will listed below More on stackoverflow.com
๐ŸŒ stackoverflow.com
June 15, 2015
INSERT XML into SQL Server 2008 database - Stack Overflow
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 ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to insert XML data into SQL Server table using XmlTextReader in C# console app? - Stack Overflow
I have a 4GB XML file. Some of its values I have to insert into a table in the database. I wrote a stored procedure and the code in the c# console but it is not inserting the data into the database... More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 12, 2018
๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ blogs โ€บ insert-xml-data-in-database-using-stored-procedure-in-sql-server
Insert XML Data In Database Using Stored Procedure In SQL Server
March 24, 2018 - Let's create a Temp Table with the name #tblXMLData to store XML Data. In this Table, I will take 4 columns with name EmployeNum, EmployeName, Designation and Department Name. ... Now, let's create a procedure for inserting XML Data into #tblXMLData ...
๐ŸŒ
MSSQLTips
mssqltips.com โ€บ home โ€บ importing and processing data from xml files into sql server tables
Importing and Processing data from XML files into SQL Server tables
February 24, 2022 - Import XML data from an XML file into SQL Server table using the OPENROWSET function ... I have an XML file downloaded from my FTP location to a local folder and data in this XML file looks like below. You can download the sample data here.
๐ŸŒ
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 - 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. Using XML data type, pass XML to the database.
๐ŸŒ
ASPSnippets
aspsnippets.com โ€บ questions โ€บ 184246 โ€บ Insert-XML-data-in-SQL-Table-using-C-and-VBNet-in-ASPNet
Insert XML data in SQL Table using C and VBNet in ASPNet
May 23, 2019 - <asp:Button ID="Button1" Text="Upload XML" runat="server" OnClick="UploadXML" /> <br /> <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="CustomerId" HeaderText="CustomerId" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="Country" HeaderText="Country" /> </Columns> </asp:GridView> ... using System.Data; using System.Configuration; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Xml;
Find elsewhere
๐ŸŒ
T-SQL Tutorial
tsql.info โ€บ xml โ€บ insert-xml-into-sql-table.php
Insert XML into SQL table in SQL Server - T-SQL Tutorial
Create a table in SQL Server that has a column of data type XML to store the XML data. For example, let's create a table called MyXmlTable with a single column called XmlData of type XML: ... Prepare the XML data that you want to insert into the table. You can either write the XML data directly ...
๐ŸŒ
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 - Now user would like to update old data & if the record does not into a table then insert that record. Here I am using @EmployeeXML_Old XML to insert data which contains some records and @EmployeeXML contains updated data as well as new data, I am using match condition to update the data as well as insert the data. ... Summary In this article, we learned Bulk Insert, Update XML data into SQL Table.
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ sql โ€บ relational-databases โ€บ xml โ€บ load-xml-data
Load XML data - SQL Server | Microsoft Learn
March 20, 2023 - INSERT INTO T SELECT 10, xCol FROM (SELECT * FROM OPENROWSET (BULK 'C:\MyFile\xmlfile.xml', SINGLE_BLOB) AS xCol) AS R(xCol); SQL Server stores XML data in Unicode (UTF-16). XML data retrieved from the server comes out in UTF-16 encoding.
๐ŸŒ
Devart
devart.com โ€บ dbforge โ€บ sql โ€บ data-pump โ€บ import-from-xml-to-sql-server.html
Import XML File into SQL Server - using Data Pump
If you select a new table as a target data source, only the Append mode can be used. ... Optionally, you can select the Use a single transaction and Use bulk insert checkboxes, the latter of which reduces the quantity of statements and speeds ...
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ sql โ€บ t-sql โ€บ xml โ€บ insert-xml-dml
insert (XML DML) - SQL Server | Microsoft Learn
December 17, 2024 - In the example, you first create a table (T) with a typed xml column, in the AdventureWorks database. You then copy a manufacturing instructions XML instance from the Instructions ...
Top answer
1 of 2
1
            using (XmlTextReader reader = new XmlTextReader("D:\\test.xml"))
            {
                while (reader.Read())
                {
                    SqlCommand insertCommand = new SqlCommand("spInsertimiListes", conn);

                    if (reader.IsStartElement("Name_details"))
                    {
                        first_name = " ";
                        middle_name = " ";
                        surname = " ";
                        gender = " ";
                        occ_title = " ";

                        while(reader.Read() && reader.IsStartElement())
                        {
                            switch(reader.Name)
                            {
                                case "FirstName":
                                    first_name = reader.ReadString();
                                    break;
                                case "MiddleName":
                                    middle_name = reader.ReadString();
                                    break;
                                case "Surname":
                                    surname = reader.ReadString();
                                    break;
                                case "Gender":
                                    gender = reader.ReadString();
                                    break;
                                case "OccTitle":
                                    occ_title = reader.ReadString();
                                    break;
                                default:
                                    throw new InvalidExpressionException("Unexpected tag");
                            }
                            reader.ReadEndElement();
                        }
                    }

                    insertCommand.CommandType = CommandType.StoredProcedure;

                    insertCommand.Parameters.AddWithValue("FirstName", first_name);
                    insertCommand.Parameters.AddWithValue("MiddleName", middle_name);
                    insertCommand.Parameters.AddWithValue("Surname", surname);
                    insertCommand.Parameters.AddWithValue("Gender", gender);
                    insertCommand.Parameters.AddWithValue("OccTitle", occ_title);

                    if (!((first_name == " " && surname == " " && middle_name == " " && gender == " " && occ_title == " ")))
                    {
                        insertCommand.ExecuteNonQuery();
                    }
                }
            }
2 of 2
0

The problem is reader.read() will read only the root node and there is only one node, so it won't move to next node. You should be navigating to child nodes by using ReadToDescendant method. The below code might work for you. Check my comments in the code.

          using (XmlTextReader reader = new XmlTextReader("D:\\test.xml"))
                {
                    reader.ReadToFollowing("Person"); // it will read the first node
                    if (reader.ReadToDescendant("Name_details")) // it will read the first descendent of Person
                    {
                        do
                        {
                            SqlCommand insertCommand = new SqlCommand("spInsertimiListes", conn);

                            if (reader.IsStartElement())
                            {
                                first_name = " ";
                                middle_name = " ";
                                surname = " ";
                                gender = " ";
                                occ_title = " ";

                                foreach (var item in reader.Name)
                                {
                                    if (reader.Name == "FirstName")
                                    {
                                        first_name = reader.ReadString();
                                    }
                                    else if (reader.Name == "MiddleName")
                                    {
                                        middle_name = reader.ReadString();
                                    }
                                    else if (reader.Name == "Surname")
                                    {
                                        surname = reader.ReadString();
                                    }
                                    else if (reader.Name == "Gender")
                                    {
                                        gender = reader.ReadString();
                                    }
                                    else if (reader.Name == "OccTitle")
                                    {
                                        occ_title = reader.ReadString();
                                    }
                                }
                            }

                            insertCommand.CommandType = CommandType.StoredProcedure;

                            insertCommand.Parameters.AddWithValue("FirstName", first_name);
                            insertCommand.Parameters.AddWithValue("MiddleName", middle_name);
                            insertCommand.Parameters.AddWithValue("Surname", surname);
                            insertCommand.Parameters.AddWithValue("Gender", gender);
                            insertCommand.Parameters.AddWithValue("OccTitle", occ_title);

                            if (!((first_name == " " & surname == " " & middle_name == " " & gender == " " & occ_title == " ")))
                            {
                                insertCommand.ExecuteNonQuery();
                            }
                        } while (reader.ReadToNextSibling("Name_details")); // it will read next descendent of person
                    }
                }
๐ŸŒ
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 - This function is native to T-SQL. It allows us to read data from many different file types through the BULK import feature, which allows the import from lots of file types, like XML. Here is the code to read the XML file and to INSERT the data into a table.
๐ŸŒ
SQL Shack
sqlshack.com โ€บ working-with-xml-data-in-sql-server
Working with XML Data in SQL Server
October 11, 2019 - XML is one of the most popular data formats for information exchange. In this article, we saw how we can create a document using XML from a SQL table. We also saw how to import into a table in SQL from an XML document.
๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ blogs โ€บ insert-xml-data-into-sql-server1
Insert XML data into SQL Server
May 3, 2012 - We couldn't retrieve the text content. Possibly it's a huge drawback with this filestream datatype. create table XMLData(id int identity(1,1),xmlFileName varchar(100),xml_data xml,o
Top answer
1 of 2
2
DECLARE @XML AS XML= N'
<Entity>
    <name>John</name>
    <aliases><alias>Johnny</alias></aliases>
    <aliases><alias>Johnson</alias></aliases>
    </Entity>
    <Entity>
    <name>Smith</name>
    <aliases><alias>Smithy</alias></aliases>


     <aliases><alias>Schmit</alias></aliases>
        </Entity>'

INSERT INTO @tblTest(firstName,LastName)
        SELECT  t1.c.value('../name[1]','varchar(100)') As FirstName,t1.c.value('alias[1]','varchar(50)') as SecondName

    FROM @xml.nodes('/Entity/aliases') t1(c)
2 of 2
1

First of all: Your XML is not well-formed as it is missing a root node. SQL-server can deal with XML-fragments, but other engines might fail...

You have a 1:n related two level hierarchy. This is best queried with a cascade of .nodes():

DECLARE @XML AS XML= 
N'<Entity>
    <name>John</name>
    <aliases>
    <alias>Johnny</alias>
    </aliases>
    <aliases>
    <alias>Johnson</alias>
    </aliases>
</Entity>
<Entity>
    <name>Smith</name>
    <aliases>
    <alias>Smithy</alias>
    </aliases>
    <aliases>
    <alias>Schmit</alias>
    </aliases>
</Entity>' 

--the query will use .nodes() to get all entities and a second time .nodes() to get a derived table of the aliases below each entity.

SELECT  A.ent.value('(name/text())[1]','varchar(100)') As FirstName
       ,B.ali.value('(alias/text())[1]','varchar(50)') as SecondName
FROM @xml.nodes('/Entity') A(ent)
CROSS APPLY A.ent.nodes(N'aliases') AS B(ali);

UPDATE added attributes

According to one comment below I changed this a bit to reflect multiple aliases with an attribute.

DECLARE @XML AS XML= 
N'<Entity>
    <name>John</name>
    <aliases>
    <alias nr="1">Johnny</alias>
    <alias nr="2">OneMore</alias>
    </aliases>
    <aliases>
    <alias>Johnson</alias>
    </aliases>
</Entity>
<Entity>
    <name>Smith</name>
    <aliases>
    <alias nr="1">Smithy</alias>
    </aliases>
    <aliases>
    <alias nr="1">Schmit</alias>
    </aliases>
</Entity>' 

SELECT  A.ent.value('(name/text())[1]','varchar(100)') As FirstName
       ,B.ali.value('@nr','int') as SomeAttribute
       ,B.ali.value('text()[1]','varchar(50)') as SecondName
FROM @xml.nodes('/Entity') A(ent)
CROSS APPLY A.ent.nodes(N'aliases/alias') AS B(ali);

What has changed?

  • .nodes() is diving one level deeper to /alias, thus repeating multiple aliases in multiple rows.
  • reading the attribute with a leading @