0

I'm having list of ids and I want to update the database table. I'm doing something like this:

sql = "update table set col = 'something' where id in (@Ids)"

using (var connection = new SqlConnection(_connection)){
   connection.Query(sql, new { Ids = ids});
}

The error is:

System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'

1
  • There's plenty examples out there of how to do this. Here's one Commented Apr 20, 2020 at 11:09

2 Answers 2

1

the simpleset way is this:

var parameters = new string[ids.Length];
var cmd = new SqlCommand();
for (int i = 0; i < ids.Length; i++)
{
    parameters[i] = string.Format("@Id{0}", i);
    cmd.Parameters.AddWithValue(parameters[i], ids[i]);
}

  cmd.CommandText = string.Format("update table set col = 'something' where id in ({0})", string.Join(", ", parameters));
Sign up to request clarification or add additional context in comments.

Comments

0

Solution : This is working for me

sql = "update table set col = 'something' where id in ("+string.Join(",", ids) + ");";

using (var connection = new SqlConnection(_connection)){
   connection.Query(sql);
}

1 Comment

Don't use string concatenation to build SQL Query, it causes SQL Injections. See: stackoverflow.com/questions/332365/…

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.