1

Here is the way I try to execute an sql command:

List<int> idsToDelete = new List<int>() { 1, 2, 3 };

string sqlDel = @"DELETE FROM products WHERE product_id IN (:idsToDelete)";

using (OracleCommand cmdDel = new OracleCommand(sqlDel, connexion))
{
    cmdDel.Parameters.Add("idsToDelete", idsToDelete.ToArray());
    cmdDel.ExecuteNonQuery();
}

I get the following exception:

Unable to cast an object form type 'System.Int32[]' to type 'System.IConvertible'.

I get the same exception with the following command:

string sqlDel = @"DELETE FROM products WHERE product_id IN :idsToDelete";

I ther a proper way to set a mutli value parameter for an IN condition? I don't want to format the command string, because it has to be reusable.

2
  • Do you want the resulting SQL to be "... IN (1,2,3)"? Commented Oct 21, 2019 at 9:37
  • string sqlDel = $@"DELETE FROM products WHERE product_id IN ({string.Join(", ", idsToDelete)})"; or you have to create a parameter for each item in idsToDelete Commented Oct 21, 2019 at 9:39

3 Answers 3

2

You can either join items into IN

List<int> idsToDelete = new List<int>() { 1, 2, 3 };

string sqlDel = 
  $@"DELETE 
       FROM products 
      WHERE product_id IN ({string.Join(", ", idsToDelete)})";

using (OracleCommand cmdDel = new OracleCommand(sqlDel, connexion))
{
    cmdDel.ExecuteNonQuery();
}

Or create parameter for each item within idsToDelete:

string sqlDel = 
  $@"DELETE 
       FROM products 
      WHERE product_id IN ({string.Join(", ", Enumerable.Range(0, idsToDelete).Select(i => $":prm_Del{i}"))})";

using (OracleCommand cmdDel = new OracleCommand(sqlDel, connexion))
{
    for (int i = 0; i < idsToDelete.Count; ++i) {
      //TODO: A better choice is explict parameter creation:
      //   cmdDel.Parameters.Add($":prm_Del{i}", idsToDelete[i], OracleType);  
      cmdDel.Parameters.AddWithValue($":prm_Del{i}", idsToDelete[i]);
    }

    cmdDel.ExecuteNonQuery();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Don't know whether this is best practice, but it should work:

List<int> idsToDelete = new List<int>() { 1, 2, 3 };

string sqlDel = @"DELETE FROM products WHERE product_id IN (";
sqlDel += string.Join(", ", idsToDelete);
sqlDel += ")";

using (OracleCommand cmdDel = new OracleCommand(sqlDel, connexion))
{
    cmdDel.Parameters.Add("idsToDelete", idsToDelete.ToArray());
    cmdDel.ExecuteNonQuery();
}

Let me know if it helped.

1 Comment

You are not using an OracleParameter as requested, and idsToDelete parameter is added but not used in the request so it is useless...
0

Try String.Join()

cmdDel.Parameters.Add("idsToDelete", string.Join(",", idsToDelete));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.