SoFunction
Updated on 2025-03-06

C# implements SQL batch insertion data into tables

This article describes the method of C# implementing SQL batch insertion data into tables. Share it for your reference, as follows:

#region Help Example: SQL Batch Insert Data Various Methods/// <summary>
/// SqlBulkCopy inserts data into the database in batches/// </summary>
/// <param name="sourceDataTable">Data Source Table</param>/// <param name="targetTableName">Target table on the server</param>/// <param name="mapping">Create a new column map and reference the column names of the source and target columns using the column number.  </param>public static void BulkToDB(DataTable sourceDataTable, string targetTableName, SqlBulkCopyColumnMapping[] mapping)
{
  /* Call method - written on November 16, 2012
   //DataTable dt = Get_All_RoomState_ByHID();
   //SqlBulkCopyColumnMapping[] mapping = new SqlBulkCopyColumnMapping[4];
   //mapping[0] = new SqlBulkCopyColumnMapping("Xing_H_ID", "Xing_H_ID");
   //mapping[1] = new SqlBulkCopyColumnMapping("H_Name", "H_Name");
   //mapping[2] = new SqlBulkCopyColumnMapping("H_sName", "H_sName");
   //mapping[3] = new SqlBulkCopyColumnMapping("H_eName", "H_eName");
   //BulkToDB(dt, "Bak_Tts_Hotel_Name", mapping);
   */
  SqlConnection conn = new SqlConnection();
  SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);  // Use data from other sources to effectively load the SQL server table in batches   = targetTableName;  //The name of the target table on the server   = ;  //The number of rows in each batch  try
  {
    ();
    if (sourceDataTable != null &amp;&amp;  != 0)
    {
      for (int i = 0; i &lt; ; i++)
        (mapping[i]);
      //Copy all rows from the provided data source to the target table      (sourceDataTable );  
    }
  }
  catch (Exception ex)
  {
    //throw ex;
    ("BulkToDB", );
  }
  finally
  {
    ();
    if (bulkCopy != null)
      ();
  }
}
/// &lt;summary&gt;
/// Custom table types can be supported only on SQL2008: Call stored procedure cursor - batch insert data into the database, pay attention/// &lt;/summary&gt;
/// &lt;param name="sourceDataTable"&gt;&lt;/param&gt;
public void DataTableToHotelDB(DataTable sourceDataTable)
{
  /* - Written on November 15, 2012
     ALTER PROCEDURE [dbo].[P_InsertSubject]
     @tempStudentID int
     AS
     DECLARE rs CURSOR LOCAL SCROLL FOR
     select H_ID from Tts_Hotel_Name
     OPEN rs
     FETCH NEXT FROM rs INTO @tempStudentID
     WHILE @@FETCH_STATUS = 0
     BEGIN
     Insert student (tempStudentID) values ​​(@tempStudentID)
     FETCH NEXT FROM rs INTO @tempStudentID
     END
     CLOSE rs
    *************************************************************************
    * create table Orders
     (
     Orders_ID int identity(1,1) primary key,
     ItemCode nvarchar(50) not null,
     UM nvarchar(20) not null,
     Quantity decimal(18,6) not null,
     UnitPrice decimal(18,6) not null
     )
     --Create user-defined table types in Programmability->Type->User-defined table types
     create type OrdersTableType as table
     (
     ItemCode nvarchar(50) not null,
     UM nvarchar(20) not null,
     Quantity decimal(18,6) not null,
     UnitPrice decimal(18,6) not null
     )
     go
     create procedure Pro_Orders
     (
       @OrdersCollection OrdersTableType readonly
     )
     as
     insert into Orders([ItemCode],[UM],[Quantity],[UnitPrice])
       SELECT oc.[ItemCode],oc.[UM],[Quantity],oc.[UnitPrice] FROM @OrdersCollection AS oc;
     go
    *
    */
  SqlParameter[] parameters = {new SqlParameter("@OrdersCollection", )};
  parameters[0].Value = sourceDataTable;
  new SQLHelper().ExecuteScalar("P_DataTable_ToHotelDB", parameters, true);
}
#endregion

For more information about C# related content, please check out the topic of this site:C# data structure and algorithm tutorial》、《Tutorial on the usage of common C# controls》、《Introduction to C# object-oriented programming tutorial"and"Summary of thread usage techniques for C# programming

I hope this article will be helpful to everyone's C# programming.