如何将参数传递给sql“in”陈述?
我想创建这个查询:
select * from products where number in ('123', '234', '456');
但我找不到任何使用 Npgsql 和 NpgsqlParameter 实现此查询的示例。我尝试过这样的:
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);
但没有成功;)
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 ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将其作为数组传递:
Pass it as an array:
您需要动态创建命令字符串 - 循环,第一个参数为 :num0,第二个参数为 :num1 等。添加完所有参数后,删除最后一个字符“,”并将其替换为“)”。
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 ")".
除了@Quassnoi 的答案之外,我还将添加这个答案来展示我们如何在实际代码中完成它。
警告!该工作代码来自真实项目,可能会损坏您的漂亮方法!
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!
使用“从 id IN 的测试中删除(选择 unnest(@ids))”
use "delete from test where id IN (select unnest(@ids))"
更新了〜2021年的答案:
您可以像这样使用
ANY
:然后,当您添加参数时,请执行以下操作:
Updated answer for ~2021:
You can use
ANY
like this:Then when you add your params, do this: