首页 > 解决方案 > 在 Postgres 中使用存储过程更新多行

问题描述

我试图弄清楚如何使用对象数组更新 postgres 表。我希望数组中的每个对象都对应一个新行,每个键对应一个列,每个值是要插入该列的数据。

还想知道如何在 c# 中调用该过程?

这里的数据格式:

[
    { col1: a, col2: 5, col3: 1, col4: one},
    { col1: b, col2: 6, col3: 2, col4: two},
    { col1: c, col2: 7, col3: 3, col4: three},
    { col1: d, col2: 8, col3: 4, col4: four},
]  

这是我的预期输出:

 col1   (varchar)| col2 (integer) |   col3 (integer)   |   col4 (varchar)
-----------------+----------------+--------------------+------------------
    a            |  5             |     1              |    one
    b            |  6             |     2              |    two
    c            |  7             |     3              |    three
    d            |  8             |     4              |    four   

 I am passing the data format as array in stored procedure.
    But want to know, how to cal the SP from c#?


The stored procedure I have written is:  

CREATE OR REPLACE FUNCTION dbo.sp_insertorupdatereadings(d dbo.reading[])
  RETURNS boolean AS
$BODY$
DECLARE

begin
--Update min values
update dbo.reading set 
  p7_1_5_1_0_first =subquery.p7_1_5_1_0_first,
  p7_1_5_1_0_last =subquery.p7_1_5_1_0_last,
  p7_1_5_2_0_first=subquery.p7_1_5_2_0_first,
  p7_1_5_2_0_last=subquery.p7_1_5_2_0_last
  From (select * from unnest(d)) as subquery
  where dbo.reading.p7_1_5_1_0_first= subquery.p7_1_5_1_0_first;

-- insert new records
  insert into dbo.reading 
select * from unnest(d) as inserd where (id) not in (select id from dbo.reading);
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION dbo.reading(dbo.reading[])
  OWNER TO postgres;

标签: c#postgresqlstored-procedures

解决方案


实际查看存储过程和任何相关的 .NET 对象将是一个巨大的帮助,所以我能提供的大部分建议只是名义上的。

与其他使用CommandType命令对象属性的 ADO 适配器不同,对于 NpgSql/PostgreSQL,您可以使用 select 命令调用存储过程:

using (NpgsqlCommand cmd = new NpgsqlCommand("select my_stored_proc()", conn))
{
    cmd.ExecuteNonQuery();
}

如果您有参数,它遵循与任何其他命令(选择、插入、更新)相同的模式:

using (NpgsqlCommand cmd = new NpgsqlCommand("select my_stored_proc(:P1, :P2)", conn))
{
    cmd.Parameters.AddWithValue("P1", "foo");
    cmd.Parameters.AddWithValue("P2", 3.14);
    cmd.ExecuteNonQuery();
}

你提到你的参数是一个数组......但我认为你不能拥有一个混合数据类型的 Postgres 数组,可以吗?当然,在 C# 中,您可以拥有一个对象数组,但我认为这不能完全转换为 PostgreSQL 数组。

下面是一个带有数组的参数示例,使用整数数组:

cmd.Parameters.Add(new NpgsqlParameter("NUMS", NpgsqlTypes.NpgsqlDbType.Array |
    NpgsqlTypes.NpgsqlDbType.Integer));
cmd.Parameters[0].Value = new int[3] { 1, 2, 3};

如果您可以为您的问题添加一些细节,也许我可以更好地构建答案。


推荐阅读