我有一个 .Net 应用程序,使用 Npgsql 与.Net对话 Postgresql 数据库。 我有一个postgresql函数,我试图通过 Npgsql 调用。 当我直接在 pgadmin 中运行时,该函数运行正常。 但是,当我从.Net(C#)应用程序运行它时,它会引发异常。
这是"已清理"功能版本:
CREATE OR REPLACE FUNCTION Function1(id_param integer,
date1_param date,
date2_param date)
RETURNS TABLE (
field1 character varying,
field2 character varying,
field3 bigint)
AS $$
BEGIN
RETURN QUERY
SELECT table1.field1,
table2.field2,
table3.field3
FROM table1
LEFT JOIN table2 on table1.empno = table2.empno
LEFT JOIN public.table3 on table1.docnum = table3.number
WHERE table1.entrydate >= date1_param
AND table2.date1 >= date1_param
AND table2.date2 <= date2_param;
END;
$$ LANGUAGE plpgsql;
以下是我在运行时获得的异常:
{&#34; 42P01:对表\&#34; table1 \&#34;&#34;}
的FROM子句条目的无效引用
我的函数中的JOIN语句导致此异常有什么问题?
谢谢, JohnB
答案 0 :(得分:1)
我无法确定错误,但我可以告诉你我在NpgSql中成功调用函数的方法并将其应用到你的例子中。
首先,您的代码,我最了解它:
NpgsqlCommand command = null;
DataTable dtResults = new DataTable();
command = new NpgsqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = functionName;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
da.Fill(dtResults);
在PostgreSQL中,函数和存储过程之间存在模糊的行(在我的最佳评估中)。为了调用函数,最简单的方法是使用select
,即使它没有返回任何内容(尽管你的确有),然后使用普通DbDataReader
或{{ 1}}。
此外,您的上述示例保证参数,其中没有一个出现在C#调用中。
最后,存储过程不显示完全限定的表。是否有可能它在psql中作为不同的用户ID运行,就像在.NET应用程序中一样?无论哪种方式,添加模式名称都没有坏处。
以下是我推荐的.NET代码:
DbDataAdapter
同样,即使您不需要它们,我也会在表格和函数前面添加架构名称。