Monday, 29 April 2013

Bulk insert and update in Asp.net


In asp.net using C# there is a big question how to update multiple records. without hitting database for each record. The answer is update in bulk. Take multiple records into "Datatable" and use string builder to do the bulk updation into your Database. 

public void bindGrd()
{
      DataTable dt = new DataTable();
      dt.Columns.Add(new DataColumn("lblUserID"typeof(int)));
      dt.Columns.Add(new DataColumn("Name"typeof(string)));
      dt.Columns.Add(new DataColumn("Country"typeof(string)));
      for (int i = 0; i < 10; i++)
      {
           dr = dt.NewRow();
           dr["UserID"] = 1;                 // Find Control 
           dr["Name"] = "XYZ";               // Find Control 
           dr["Country"] = "PQR";            // Find Control
           dt.Rows.Add(dr);
     }
     grdUpdate.DataSource = dt;
     grdUpdate.DataBind();
}

On Update Button Click ->

protected void btn_Click(sender obj, Eventargs e)
{
      StringBuilder sb = new StringBuilder();
      sb.Append("<root>"); 
      for (int i = 0; i < gvCustomer.Rows.Count; i++)
      {
          Label lblID grdUpdate.Rows[i].FindControl("UserID"as Label;
          TextBox txtNamegrdUpdate.Rows[i].FindControl("txtName"as TextBox;
          TextBox txtCountry = grdUpdate.Rows[i].FindControl("txtCountry"as TextBox;
           if(lblID.Text.Length > 0)
           {
                sb.Append("<row ID='" + lblID.Text.Trim() + "' Name='" + txtName.Text.Trim() +  "' Country='" + txtCountry.Text.Trim() + "'/>");
           }
      }
      sb.Append("</root>"); 
      bulkUpdate(sb);
}

Method which call your stored procedure :-

public static bool bulkUpdate(StringBuilder sb)
{
       string conStr = WebConfigurationManager.     ConnectionStrings["DB"].ConnectionString;
      using(SqlConnection con = new SqlConnection(conStr))
      {
            SqlCommand cmd = new SqlCommand("sp_UpdateRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@XMLBulkUpdate", sb.ToString());
            con.Open();
            cmd.ExecuteNonQuery();
            con.close();
      }
}

Stored Procedure for Update in Bulk

CREATE PROCEDURE [dbo].[sp_UpdateRecords]
(
 @XMLBulkUpdate XML
)
AS
BEGIN

      Update tbl   set          
            Name = TempData.Item.value('@Name', 'VARCHAR(50)'),
            Country = TempData.Item.value('@Country', 'VARCHAR(50)')
      FROM @XMLBulkUpdate.nodes('/root/row') AS TempData(Item)
   where 
       ID =  TempData.Item.value('@ID', 'INT'),

RETURN 0
END

And if you want to bulk update then change your procedure from Update to insert :

Insert into tbl(ID,Name,Country)
       Select        
            ID =  TempData.Item.value('@ID', 'INT'),   
            Name = TempData.Item.value('@Name', 'VARCHAR(50)'),
            Country = TempData.Item.value('@Country', 'VARCHAR(50)')
      FROM @XMLBulkUpdate.nodes('/root/row') AS TempData(Item)

       

No comments:

Post a Comment