繁体   English   中英

为什么我通过.Net中的npgsql遇到运行函数(存储过程)的异常?

[英]Why am I getting exceptions running a function (stored procedure) through npgsql in .Net?

我有一个.Net应用程序,它使用Npgsql for .Net与Postgresql DB通讯。 我有一个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;  

这是我在运行时遇到的异常:

{“ 42P01:对表\\“ table1 \\”“的FROM子句条目的无效引用}

我的函数中的JOIN语句导致此异常的原因是什么?

谢谢,JohnB

我不能肯定地说出了什么问题,但是我可以告诉您我在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 ,即使它不返回任何内容(尽管您返回了),然后使用普通的DbDataReaderDbDataAdapter

此外,以上示例保证了参数,但这些参数均未出现在C#调用中。

最后,存储过程不显示完全限定的表。 它是否可以像在.NET应用程序中一样以不同的用户ID在psql中运行? 无论哪种方式,添加架构名称都没有害处。

这是我为您的.NET代码推荐的内容:

NpgsqlCommand command = new NpgsqlCommand("select * from Function1(:ID, :DATE1, :DATE2)",
    connection);
command.Parameters.Add(new NpgsqlParameter("ID", NpgsqlDbType.Integer));
command.Parameters.Add(new NpgsqlParameter("DATE1", NpgsqlDbType.Date));
command.Parameters.Add(new NpgsqlParameter("DATE2", NpgsqlDbType.Date));

command.Parameters[0].Value = id;
command.Parameters[1].Value = dt1;
command.Parameters[2].Value = dt2;

DataTable dtResults = new DataTable();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
da.Fill(dtResults);

同样,即使您不需要它们,我也会在表和函数的前面添加模式名称。

暂无
暂无

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

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