SQL Bulk Copy From DataTable Using XML

In this article, you will learn about SQL bulk copy from DataTable using XML.

To copy data from DataTable or DataSet to SQL Server, we need to use either a foreach or a for loop. It is OK when the count of rows is reasonable. But if the data is like 1 lakh or 1 crore, then it is not possible to round the loop for that much time. Then what do we do? A simple method to follow is to use XML. I am sure you all are more or less aware of this XML. It's like a database with tags. Or, it's better to say it's a database. It keeps data in a file with an extension of ".xml".

Our intention is to convert the DataTable's data into an XML file and send it to the server, where with the help of a stored procedure, we will extract data and insert into the database table. So let's come and see how to do this...

First of all, create a new database and create a new table, name it as you want. Database table structure will be like this.

  1. Name NVarChar(255) not null  
  2. Address NVarChar(255) not null  
  3. Phone NvarChar(12) not null  

OK, now, we need to create a new DataTable and put some data in it. Make sure your column and the database table's column are the same.

  1. DataTable dt = new DataTable();  
  2. dt.Columns.Add("Name");  
  3. dt.Columns.Add("Address");  
  4. dt.Columns.Add("Phone");  
  6. dt.Rows.Add("Arkadeep""Kolkata""123456890");  
  7. dt.Rows.Add("Saikat""Chennai""99999999");  
  8. dt.Rows.Add("Rahul""Delhi""9876543210");  

Now, you have to convert this DataTable into XML. To do this, copy and paste the following code after the DataTable section.

  1. private static string ConvertToXML(DataTable dt)  
  2. {  
  3.       DataSet dsBuildSQL = new DataSet();  
  4.       StringBuilder sbSQL;  
  5.       StringWriter swSQL;  
  6.       string XMLformat;  
  7.       try  
  8.       {  
  9.            sbSQL = new StringBuilder();  
  10.            swSQL = new StringWriter(sbSQL);  
  11.            dsBuildSQL.Merge(dt, true, MissingSchemaAction.AddWithKey);  
  12.            dsBuildSQL.Tables[0].TableName = "DataTable";  
  13.            foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)  
  14.            {  
  15.                col.ColumnMapping = MappingType.Attribute;  
  16.            }  
  17.            dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);  
  18.            XMLformat = sbSQL.ToString();  
  19.            return XMLformat;  
  20.        }  
  21.        catch (Exception sysException)  
  22.        {  
  23.            throw sysException;  
  24.        }  
  25. }  

Call this method to convert the DataTable to XML.

  1. String xmlData = ConvertToXML(dt);  

Now, pass the value to the stored procedure in the following way.

  1. SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ToString());  
  2. SqlCommand command = new SqlCommand("sp_InsertData '" + xmlData + "'", conn);  
  3. conn.Open();  
  4. command.ExecuteNonQuery();  
  5. conn.Close();  

Now, let's check the stored procedure sp_InsertData.

  1. CREATE PROCEDURE sp_InsertData  
  2. (@xmlString VARCHAR(MAX))  
  3. AS  
  4. BEGIN  
  6.       DECLARE @xmlHandle INT  
  8.       DECLARE @stagingTable TABLE  
  9.       (  
  10.          [Name]               VARCHAR(50),  
  11.          [Address]            VARCHAR(50),  
  12.          [Phone]              VARCHAR(50)  
  13.       )  
  15.       EXEC sp_xml_preparedocument @xmlHandle output, @xmlString    
  17.       INSERT INTO@stagingTable   
  18.       SELECT  [Name]    ,  
  19.                   [Address],  
  20.                   [Phone]       
  21.       FROM  OPENXML (@xmlHandle, '/DataTable',1)  
  22.                         WITH ([Name]            varchar(50)       '@Name',  
  23.                                 [Address]       varchar(50)       '@Address',  
  24.                                 [Phone]         varchar(50)       '@Phone'  
  25.                                )  
  27.       INSERT INTOSampleData ([Name], [Address], [Phone])  
  28.             (SELECT [Name] , [Address],[Phone]FROM @stagingTable)  
  30.       EXEC sp_xml_removedocument @xmlHandle  
  31. END