I am doing some research, to get a better understanding for SQL and working with DataTables. So I was trying to work on good performance reading data from a MS SQL database and load it into a datagridview.
I've created a SQL function, which I am calling from my tool and load the results into a datatable. If I execute this function within SSMS it takes 11-12 seconds to load the results (almost 1,5 million entries), but if I am executing this function by using the tool, I coded, it will take more than 30 seconds (just for doing DataTable.Load(SqlDataReader))
What I've done so far is:
private DataTable GetDataFromDB(string userId, string docId, DateTimeOffset date)
{
string cmd = String.Format("select * from dbo.GetData(@userId, @docId, @dueDate);");
using (SqlConnection conn = new SqlConnection(connectionString))
{
if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand command = new SqlCommand(cmd, conn);
if (String.IsNullOrEmpty(userId))
command.Parameters.AddWithValue("@userId", DBNull.Value);
else
command.Parameters.AddWithValue("@userId", userId);
if (String.IsNullOrEmpty(docId))
command.Parameters.AddWithValue("@docId", DBNull.Value);
else
command.Parameters.AddWithValue("@docId", docId);
command.Parameters.AddWithValue("@dueDate", dueDate);
SqlDataReader reader = command.ExecuteReader();
stopWatch.Reset();
stopWatch.Start();
table.BeginLoadData();
table.Load(reader, LoadOption.Upsert);
table.EndLoadData();
stopWatch.Stop();
reader.Close();
reader.Dispose();
conn.Close();
}
return table;
}
I've already done some google research and this is the best I could come up with. So far it is working well, but I am curios if it is possible to get the results faster. Any ideas? Also I have a problem with the memory. As soon as I start the call, the tool will allocate up to 900MB RAM, until it has all the entries. I've already managed it, to free the memory everytime I call the function above, but I think, 900MB are quite a lot and another problem is, that it won't release all the RAM, which was needed. So for example: When I start the tool, it needs roundabout 7MB of RAM, if I call the method above the first time, it will need 900MB. If I call it the next time, it will release most of the memory, but will still need 930MB. The third time 960MB and so on. So, with every call it allocates more memory, which will cause a "System out of memory"-Exception, if this method get called often.
Thank you a lot!