[英]How to do ExecuteScalar Function with Npgsql and PostgreSQL?
I am learning Npgsql and PostgrSQL. 我正在学习Npgsql和PostgrSQL。 I am unable to get this simple test to work. 我无法通过这个简单的测试来工作。 Here is my function: 这是我的功能:
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;
Here is my C# code: 这是我的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);
}
I keep getting the error below. 我不断收到以下错误。
Npgsql.NpgsqlException : ERROR: 42601: query has no destination for result data Npgsql.NpgsqlException:错误:42601:查询没有结果数据的目的地
This is nothing to do with nPgSQL. 这与nPgSQL无关。 Your problem is in your stored function. 您的问题出在您的存储函数中。
You've written a trivial wrapper in PL/PgSQL, but you haven't used RETURN
. 您已经在PL / PgSQL中编写了一个简单的包装器,但尚未使用RETURN
。 You can't use SELECT
in PL/PgSQL except when its output goes to a variable (via SELECT INTO
or as a subquery like x := (SELECT ...)
or to the RETURN QUERY
statement. 您不能在PL / PgSQL中使用SELECT
,除非它的输出为变量(通过SELECT INTO
或作为子查询,如x := (SELECT ...)
或RETURN QUERY
语句)。
You should write: 您应该写:
BEGIN
RETURN QUERY
SELECT COUNT(*) FROM Customers
WHERE CustomerId = _customerid
OR _customerid is null;
END
and define your procedure as RETURNS bigint
, since obviously you cannot get a value from the function if it returns void
. 并将您的过程定义为RETURNS bigint
,因为如果函数返回void
,很显然您无法从函数中获取值。 Also, this function is STABLE
not VOLATILE
. 同样,此函数是STABLE
VOLATILE
。 If you aren't sure, say nothing. 如果不确定,请什么也不要说。 The same is true for COST
- unless you have a good reason, leave it out. COST
也是这样-除非您有充分的理由,否则就不用管它了。
This is still overcomplicated though. 但是,这仍然过于复杂。 You can use a simple sql function for calls like this, eg 您可以对这样的调用使用简单的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.