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.
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.
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 .
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}.");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.