Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to sql 'in' statement?

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

like image 548
Adrian Serafin Avatar asked Apr 18 '11 10:04

Adrian Serafin


People also ask

Can we pass parameter to function in SQL?

We can also pass dates as parameters in the SQL Server functions. In this section, we will create a function that will take a particular date as the input parameter.

Can we pass parameter in with clause?

Solution 1. You can use parameters in a WITH clause just like in a traditional statement. The problem in the example is the IN operator which requires a list of values.


1 Answers

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);
like image 199
Quassnoi Avatar answered Nov 04 '22 20:11

Quassnoi