How to pass parameter to sql 'in' statement? How to pass parameter to sql 'in' statement? postgresql postgresql

How to pass parameter to sql 'in' statement?


Pass it as an array:

string[] numbers = new string[] { "123", "234" };NpgsqlCommands cmd = new NpgsqlCommands("select * from products where number = ANY(:numbers)");NpgsqlParameter p = new NpgsqlParameter("numbers", NpgsqlDbType.Array | NpgsqlDbType.Text);p.value = numbers;command.Parameters.Add(p);


You need to dynamically create your command string - loop with your first parameter as :num0, second as :num1 etc. When you've added all of them, remove the last character "," and replace it with ")".


In addition to @Quassnoi answer I'll add this one to show, how we done it in real code.

Warning! This working code is from real project and can damage your beautiful approaches!

string commstr = "SELECT product_name, price, product_url, image_url FROM products WHERE id  = ANY(@arr);";NpgsqlCommand cm = new NpgsqlCommand(commstr, cn);NpgsqlParameter arpar = new NpgsqlParameter();arpar.ParameterName = "arr";arpar.NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Bigint;arpar.Value = PerformQuerySphinx(query, limit);cm.Parameters.Add(arpar);