I have table (about 250k rows) in Access db with date, time and name (other columns are irrelevant for this problem). I need to get just first (or last) date/time for name value and send it to new table.
I have tried SQL statement but for large number of rows it is too slow. here: Access SQL to return only first or last occurence by date
I also tried read data from db to DataTable, looping through and deleting rows that I don't want, but I'm not able to send this edited DataTable back to db. Similar to this: How do I insert a datatable into Microsoft Access?
using(OleDbConnection con = new OleDbConnection(ConnectionString))
{
SQL = "Select * From OriginalTable";
var adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(SQL, con);
var cbr = new OleDbCommandBuilder(adapter);
try
{
con.Open();
DataTable dtFilter = new DataTable();
adapter.Fill(dtFilter);
string id = dtFilter.Rows[dtFilter.Rows.Count - 1][4].ToString();
for(int i = dtFilter.Rows.Count - 2; i >= 0; i--)
{
DataRow dr = dtFilter.Rows[i];
if(dtFilter.Rows[i][4].ToString() == id)
{
dr.Delete();
}
else
{
id = dtFilter.Rows[i][4].ToString();
}
}
dtFilter.AcceptChanges(); // DataTable looks as I want
adapter.Update(dtFilter); // Returns 0
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Message, "OledbException Error");
}
catch(Exception x)
{
MessageBox.Show(x.Message, "Exception Error");
}
}
I expect to export dtFilter to Access db. Why it returns 0?
I'm open for SQL statement as long as it is fast.
UPDATE: SQL Statement used for selecting first or last entry
SELECT DISTINCT
cdate(Format(t.DateOS + t.TimeOS, 'dd.MM.yyyy HH:mm:ss')) AS DateTimeOS,
cdate(Format(t.DateOS, 'dd.MM.yyyy ')) AS DateOS,
cdate(Format(t.TimeOS, 'HH:mm:ss')) AS TimeOS,
t.EP AS EP, t.ID AS ID
FROM TestFirstLast AS t
WHERE t.EP = 'L100'
AND (((t.DateOS + t.TimeOS) > #1/1/2016 12:00:00 AM# AND (t.DateOS + t.TimeOS) <= #3/1/2016 12:00:00 AM#))
AND NOT EXISTS(SELECT 1 FROM TestFirstLast AS t2 WHERE t2.EP = t.EP AND t2.ID = t.ID AND (t2.DateOS < t.DateOS OR t2.DateOS = t.DateOS AND t2.TimeOS < t.TimeOS))
GOOD SOLUTION: I found good description of problem and solution here