Jul 24, 2008

Batch Inserts to SQL Server- Stored procedure method

To do batch Updates to SQL server

  • Create DataTable or DataSet and populate it with required rows
  • Next Create a SqlCommand and SqlDataAdapter using that SqlCommand
  • Remember to set the UpdateRowSource property on the Command the the appropriate value
  • Set the UpdateBatchSize Property on the SqlDataAdapter
  • then call SqlDataAdapter.Update(dt) to push the updates to SQL server
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("asin"));
dt.Columns.Add(new DataColumn("trackasin"));
dt.Columns.Add(new DataColumn("isrc"));
for(int i =0; i < 2000;i++)
{
DataRow dr = dt.NewRow();
dr["asin"] = asin;
dr["trackasin"] = trackasin;
dr["isrc"] = isrc;
//dr.RowState = DataRowState.Added;
dt.Rows.Add(dr);
}
------------------------------------------------
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MySpaceMusic"].ConnectionString))
{
SqlCommand command = new SqlCommand(INSERT_TRACK, connection);
command.CommandType = CommandType.StoredProcedure;
command.UpdatedRowSource = UpdateRowSource.None;
command.CommandTimeout = commandTimeout;

command.Parameters.Add("@asin", SqlDbType.VarChar, 255, dt.Columns[0].ColumnName);
command.Parameters.Add("@trackAsin", SqlDbType.VarChar, 255, dt.Columns[1].ColumnName);
command.Parameters.Add("@isrc", SqlDbType.VarChar, 600, dt.Columns[2].ColumnName);

SqlDataAdapter adpt = new SqlDataAdapter();

adpt.InsertCommand = command;
adpt.UpdateBatchSize = batchSize;
try
{
connection.Open();
int recordsInserted = adpt.Update(dt);
}
finally
{
adpt.Dispose();
}
}


kick it on DotNetKicks.com

No comments: