我有一个PostGres数据库,其中包含一个返回JSON文档的存储过程,基于以下文章:http://www.sqlines.com/postgresql/npgsql_cs_result_sets
程序如下所示:
-- Procedure that returns a single result set (cursor)
CREATE OR REPLACE FUNCTION get_data_test() RETURNS refcursor AS $$
DECLARE
ref refcursor; -- Declare a cursor variable
BEGIN
OPEN ref FOR -- Open a cursor
SELECT row_to_json(r) AS data
FROM
(
SELECT *
FROM data AS d
) r;
RETURN ref; -- Return the cursor to the caller
END;
$$ LANGUAGE plpgsql;
然后我从.net控制台应用程序运行以下代码:
// Making connection with Npgsql provider
using (NpgsqlConnection conn = new NpgsqlConnection(connstring))
{
conn.Open();
var trans = conn.BeginTransaction();
var cmd = new NpgsqlCommand("get_data_test", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = trans;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
Trace.WriteLine(reader[0]);
}
}
输出是带有refcursor名称的单个实例,而不是实际数据: <未命名的门户网站1>
如果我直接在命令文本中运行select查询,则会按预期返回结果集。我还尝试使用" SELECT get_data_test()"来通过文本显式调用proc。但这也只是光标名称而失败。
我不相信我错过了一个步骤,这个refcursor应该退回去捆绑。我做错了什么?
答案 0 :(得分:0)
碰巧,教程错了:
Nice GitHub错误报告:https://github.com/npgsql/npgsql/issues/1777
正确答案:
-- Procedure that returns a single result set (cursor)
CREATE OR REPLACE FUNCTION get_data_test() RETURNS TABLE (data JSON) AS $$
BEGIN
RETURN query
SELECT row_to_json(r) AS data
FROM
(
SELECT *
FROM data AS d
) r;
END;
$$ LANGUAGE plpgsql;