20

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

KitKat
  • 1,495
  • 14
  • 15
Adrian Serafin
  • 7,665
  • 5
  • 46
  • 67

5 Answers5

39

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);
Quassnoi
  • 413,100
  • 91
  • 616
  • 614
  • this will generate an error: your `array` variable should be `numbers` in the parameter value – Steven Ryssaert Apr 18 '11 at 10:31
  • @UwConcept: honestly, it is a long time since I last used `NPgSQL` and don't even have a `VS` installed to check :) – Quassnoi Apr 18 '11 at 10:32
  • @Adrian: is the syntax OK or you had to correct it? I cannot check. – Quassnoi Apr 18 '11 at 11:18
  • Use NpgsqlDbType | NpgsqlDbType.Numeric if you pass an int[]. Also I think its $numbers not :numbers? Other than that the syntax worked for me. – Rios Feb 13 '14 at 21:29
1

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);
KitKat
  • 1,495
  • 14
  • 15
Arman Hayots
  • 2,459
  • 6
  • 29
  • 53
1

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

Mr Shoubs
  • 14,629
  • 17
  • 68
  • 107
1

use "delete from test where id IN (select unnest(@ids))"

srini
  • 21
  • 5
0

Updated answer for ~2021:

You can use ANY like this:

WHERE id = ANY (@ids)

Then when you add your params, do this:

cmd.Parameters.AddWithValue("ids", ids.ToArray());
JacobIRR
  • 8,545
  • 8
  • 39
  • 68