简体   繁体   English

PostgreSQL 相当于 SQL Server 的 TVP

[英]PostgreSQL equivalent to SQL Server's TVP

SQL Server has Table Value Parameters which allows you to pass an array of values as a parameter. SQL Server 具有表值参数,它允许您将值数组作为参数传递。

What is the appropiate way to achieve something similar to a PostgreSQL query so I can do something like:实现类似于 PostgreSQL 查询的适当方法是什么,以便我可以执行以下操作:

select * from product where id in ($1)

I'm using Npgsql .NET library.我正在使用 Npgsql .NET 库。

https://www.nuget.org/packages/Npgsql/3.0.5 https://www.nuget.org/packages/Npgsql/3.0.5

In PostgreSQL you can use arrays instead of list of IDs like:在 PostgreSQL 中,您可以使用数组代替 ID 列表,例如:

... 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.这意味着id是数组的项目之一。

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} .其中 $1 是一个字符串参数,看起来像{1, 2, 3} Note that a space between $1 and ::int[] - it may be necessary for some clients.请注意$1::int[]之间的空格 - 对于某些客户端可能是必需的。

Not sure about C# is it supports array parameters directly.不确定 C# 是否直接支持数组参数。

In Postgres you can use IN operator in two ways:在 Postgres 中,您可以通过两种方式使用 IN 运算符:

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.这是使用 Dapper 和 Npgsql 在 C# 中插入的示例 - 它将 1, 2, 3 插入到临时表中,并按降序选择它们,因此它将打印 3 2 1 到控制台。 The trick here is the Postgres unnest() function, which expands an array to a set of rows:这里的技巧是 Postgres unnest()函数,它将数组扩展为一组行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM