I have this code in a foreach loop that calls a sql function for each folder
foreach (string strCurrentFolder in strLocalSubFolderList)
{
SqlCommand sqlComm1 = new SqlCommand("dbo.fnChkXfer", _sqlConn);
sqlComm1.CommandType = CommandType.StoredProcedure;
sqlComm1.Parameters.Add("@FileXferred",SqlDbType.Bit).Direction = ParameterDirection.ReturnValue;
sqlComm1.Parameters.AddWithValue("@UNCFolderPath", strCurrentFolder);
sqlComm1.Parameters.AddWithValue("@FileType", "Type 1");
...if files not transferred, then transfer them
SqlCommand sqlComm2 = new SqlCommand("dbo.fnChkXfer", _sqlConn);
sqlComm2.CommandType = CommandType.StoredProcedure;
sqlComm2.Parameters.Add("@FileXferred",SqlDbType.Bit).Direction = ParameterDirection.ReturnValue;
sqlComm2.Parameters.AddWithValue("@UNCFolderPath", strCurrentFolder);
sqlComm2.Parameters.AddWithValue("@FileType", "Type 2");
...if files not transferred, then transfer them
SqlCommand sqlComm3 = new SqlCommand("dbo.fnChkXfer", _sqlConn);
sqlComm3.CommandType = CommandType.StoredProcedure;
sqlComm3.Parameters.Add("@FileXferred",SqlDbType.Bit).Direction = ParameterDirection.ReturnValue;
sqlComm3.Parameters.AddWithValue("@UNCFolderPath", strCurrentFolder);
sqlComm3.Parameters.AddWithValue("@FileType", "Type 3");
...if files not transferred, then transfer the
}
It works fine, but there is a lot of duplicated code, which may be unnecessary.
Is it possible to create the SqlCommand object once outside of the loop and "reset" just the parameter values in the loop? How could I reuse the object? (Please be very specific).
Or should I continue to include this block of code in the loop, which executes the fn 3 times with different data for each iteration? It seems inefficient to keep recreating the SqlCommand object when it's almost exactly the same every time.