Reputation: 18794
SQL Server has Table Value Parameters which allows you to pass an array of values as a parameter.
What is the appropiate way to achieve something similar to a PostgreSQL query so I can do something like:
select * from product where id in ($1)
I'm using Npgsql .NET library.
https://www.nuget.org/packages/Npgsql/3.0.5
Upvotes: 2
Views: 1045
Reputation: 4647
Here's an example for inserts in C# using Dapper and Npgsql - it inserts 1, 2, 3 into a temporary table and selects them back out ordered descending, so it will print 3 2 1 to the console. The trick here is the Postgres unnest()
function, which expands an array to a set of rows:
var results = await conn.QueryAsync<int>(@"
CREATE TEMPORARY TABLE DapperNpgsqlArrayParameterDemo (id int not null primary key);
INSERT INTO DapperNpgsqlArrayParameterDemo (id) SELECT unnest(@numbers);
SELECT id from DapperNpgsqlArrayParameterDemo order by id desc;",
new { numbers = new int[] { 1, 2, 3 } });
foreach(var item in results)
{
Console.WriteLine($"found {item}.");
}
Upvotes: 1
Reputation: 15624
In PostgreSQL you can use arrays instead of list of IDs like:
... where id = any('{1, 2, 3}'::int[])
or
... where id = any(array[1, 2, 3])
which means that id
is one of the array's items.
Read more about arrays operators and functions.
To pass array as a parameter from third party languages you can use at least first variant:
... where id = any($1 ::int[])
where $1 is a string parameter looks like {1, 2, 3}
. Note that a space between $1
and ::int[]
- it may be necessary for some clients.
Not sure about C# is it supports array parameters directly.
Upvotes: 3
Reputation: 121694
In Postgres you can use IN operator in two ways:
expression IN (value [, ...])
expression IN (subquery)
Read in the documetation: first variant, second variant or this overview.
Upvotes: 1