[英]How to do ExecuteScalar Function with Npgsql and PostgreSQL?
我正在学习Npgsql和PostgrSQL。 我无法通过这个简单的测试来工作。 这是我的功能:
CREATE OR REPLACE FUNCTION count_customers(_customerid integer DEFAULT NULL::integer)
RETURNS void AS
$BODY$
BEGIN
SELECT COUNT(*) FROM Customers
WHERE CustomerId = _customerid or _customerid is null;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
这是我的C#代码:
[Test]
public void ExecuteScalarTest()
{
NpgsqlConnection conn = new NpgsqlConnection("Host=localhost; Database=postgres; User ID=postgres; Password=password");
conn.Open();
IDbCommand command = conn.CreateCommand();
command.CommandText = "count_customers";
command.CommandType = CommandType.StoredProcedure;
object result = command.ExecuteScalar();
conn.Close();
Console.WriteLine(result);
}
我不断收到以下错误。
Npgsql.NpgsqlException:错误:42601:查询没有结果数据的目的地
这与nPgSQL无关。 您的问题出在您的存储函数中。
您已经在PL / PgSQL中编写了一个简单的包装器,但尚未使用RETURN
。 您不能在PL / PgSQL中使用SELECT
,除非它的输出为变量(通过SELECT INTO
或作为子查询,如x := (SELECT ...)
或RETURN QUERY
语句)。
您应该写:
BEGIN
RETURN QUERY
SELECT COUNT(*) FROM Customers
WHERE CustomerId = _customerid
OR _customerid is null;
END
并将您的过程定义为RETURNS bigint
,因为如果函数返回void
,很显然您无法从函数中获取值。 同样,此函数是STABLE
VOLATILE
。 如果不确定,请什么也不要说。 COST
也是这样-除非您有充分的理由,否则就不用管它了。
但是,这仍然过于复杂。 您可以对这样的调用使用简单的sql函数,例如
CREATE OR REPLACE FUNCTION count_customers(_customerid integer DEFAULT NULL::integer)
RETURNS bigint LANGUAGE sql STABLE AS
$BODY$
SELECT COUNT(*) FROM Customers
WHERE CustomerId = $1 OR $1 is null;
$BODY$;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.