How to pass parameter to sql 'in' statement?

一笑奈何 提交于 2019-12-20 12:35:13

问题


I want to create this query:

select * from products where number in ('123', '234', '456');

but I can't find any example of achiving this with Npgsql and NpgsqlParameter. I tried like this:

string[] numbers = new string[] { "123", "234" };

NpgsqlCommands cmd = new NpgsqlCommands("select * from products where number in (:numbers)");
NpgsqlParameter p = new NpgsqlParameter("numbers", numbers);
command.Parameters.Add(p);

but it didn't work ;)


回答1:


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);



回答2:


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 ")".




回答3:


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);


来源:https://stackoverflow.com/questions/5701482/how-to-pass-parameter-to-sql-in-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!