How to delete tens of thousands of rows using different IDs (array) in an "MS-Access" query, with or without using the "LINQ" commands?

Reza Jaferi 331 Reputation points
2022-07-21T19:46:25.96+00:00

Hi,
I want to delete rows from an MS-Access database using an array of different IDs.
The Length of this array might vary based on DataGrid.SelectedItems.
The values of this array may also vary based on DataGrid.SelectedItems.
I tried numerous different codes, but each one has its own problems.
Note: in the following solutions, BookCodeSelectedItems is an array of uint type.
First solution (This code works correctly when the array length is not large, but for example, if the array length is 30,000, it displays the error Query is too complex):

OleDbCommand OleDbCommand_Delete = new OleDbCommand(string.Join(null, "Delete From BookTable Where BookCode In (",string.Join(",",BookCodeSelectedItems),")"), OleDbConnect);  

Second solution (When the array length is large, this code runs very slowly):

for (int i = 0; i < BookCodeSelectedItems.Length; i++)  
{  
    OleDbCommand OleDbCommand_Delete = new OleDbCommand(string.Join(null, "Delete From BookTable Where BookCode = @BookCodeSelectedItems"), OleDbConnect);  
    OleDbCommand_Delete.Parameters.AddWithValue("@BookCodeSelectedItems", BookCodeSelectedItems[i]);  
    OleDbCommand_Delete.ExecuteNonQuery();  
}  

Third solution (This code does not work properly if the user selects random rows):
223258-selected-rows.png

OleDbCommand OleDbCommand_Delete = new OleDbCommand(string.Join(null, "Delete From BookTable Where BookCode Between @BookCodeSelectedItemsFirst And @BookCodeSelectedItemsLast"), OleDbConnect);  
OleDbCommand_Delete.Parameters.AddWithValue("@BookCodeSelectedItemsFirst", BookCodeSelectedItems.First());  
OleDbCommand_Delete.Parameters.AddWithValue("@BookCodeSelectedItemsLast", BookCodeSelectedItems.Last());  

Thanks

Developer technologies | Windows Presentation Foundation
Developer technologies | .NET | Other
Developer technologies | Transact-SQL
Developer technologies | XAML
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-07-21T19:59:43.827+00:00

    Check an approach:

    for( int i = 0; i < BookCodeSelectedItems.Length; i += 20 )  
    {  
        string codes = string.Join( ",", BookCodeSelectedItems.Skip( i ).Take( 20 ) );  
        OleDbCommand OleDbCommand_Delete = new OleDbCommand( "Delete From BookTable Where BookCode In (" + codes + ")", OleDbConnect );  
        // execute the command   
        // . . .  
    }  
    
    3 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.