[英]How to construct Sql Server TVP with a non default order of columns?
[英]PostgreSQL equivalent to SQL Server's TVP
SQL Server 具有表值参数,它允许您将值数组作为参数传递。
实现类似于 PostgreSQL 查询的适当方法是什么,以便我可以执行以下操作:
select * from product where id in ($1)
我正在使用 Npgsql .NET 库。
在 PostgreSQL 中,您可以使用数组代替 ID 列表,例如:
... where id = any('{1, 2, 3}'::int[])
或者
... where id = any(array[1, 2, 3])
这意味着id
是数组的项目之一。
要将数组作为第三方语言的参数传递,您至少可以使用第一个变体:
... where id = any($1 ::int[])
其中 $1 是一个字符串参数,看起来像{1, 2, 3}
。 请注意$1
和::int[]
之间的空格 - 对于某些客户端可能是必需的。
不确定 C# 是否直接支持数组参数。
这是使用 Dapper 和 Npgsql 在 C# 中插入的示例 - 它将 1, 2, 3 插入到临时表中,并按降序选择它们,因此它将打印 3 2 1 到控制台。 这里的技巧是 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.