Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Passar lista no parâmetro SQL


Você pode parametrizar cada valor na lista em um IN cláusula:
List<string> names = new List<string> { "john", "brian", "robert" };
string commandText = "DELETE FROM Students WHERE name IN ({0})";
string[] paramNames = names.Select(
    (s, i) => "@tag" + i.ToString()
).ToArray();

string inClause = string.Join(",", paramNames);
using (var command = new SqlCommand(string.Format(commandText, inClause), con))
{
    for (int i = 0; i < paramNames.Length; i++)
    {
        command.Parameters.AddWithValue(paramNames[i], names[i]);
    }
    int deleted = command.ExecuteNonQuery();
} 

que é semelhante a:
"... WHERE Name IN (@tag0,@tag1,@tag2)"

command.Parameters["@tag0"].Value = "john";
command.Parameters["@tag1"].Value = "brian";
command.Parameters["@tag2"].Value = "robert";

Adaptado de:https://stackoverflow.com/a/337792/284240