[英]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.