Question

I want to find the optimized way for inserting multiple records in a Table from Front End. I have a Table like TableA(Id int,StudentId int,EntryTime DateTime,ClassId int,Status int). On Front End i have a DataGridView in which a specific Class Students are loaded, for example 50 Students record is loaded in DataGridView. Now for saving all these 50 records at once, i have two methods (I think so). Method 1
I will create a List and assign all data from DataGridView to List, and then by using ForEach loop i will insert record one by one, by calling Strored Procedure. e.g in C#

  SqlComm.BeginTransaction();
  foreach (ClassName d in MyList)
  {
   .....
   .....
    SqlComm.ExecuteNonQuery();
  }
  SqlComm.CommitTransaction();

MyList is a List of a User Defined Class.

Method 2:
I will create a DataTable and pass all data from DataGridView to DataTable and in Sql Server i will create a User-Defined Table Type and then will use it as argument to Stored Procedure, and in C# i will pass the DataTable to Stored Procedure, and then in Stored Procedure i will insert record in Table. In C# like this..

SqlCommand SqlComm= new SqlCommand(sqlInsert, connection);
SqlParameter tvpParam = SqlComm.Parameters.AddWithValue(
    "@myType", myDataTable);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.TableATableType";

SqlComm.ExecuteNonQuery();

My Question is that in above two methods which will be the Best way for inserting multiple records, which method will use less Resources..? Thanks

Was it helpful?

Solution

Every ExecuteNonQuery requires a round trip to the server. On your local machine, you may not measure much overhead, but in general (assuming that your code to populate the table is reasonable, and the code using the table on the SQL side is also reasonable), I'd expect method 2 to be more efficient.

Also, generally, if you've not got any other code involving transactions, then the first method will have to create and commit 50 transactions, whereas the second should be able to run inside a single transaction, which should enable the file I/O costs to be lower also.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top