我有一个返回多个结果集的PostgresQL函数。我可以毫不费力地在.net中提取这些结果集(所以我知道我的函数工作正常),但是在使用node-postgres时遇到了问题。
结果对象返回一个包含7个项目的数组,该数组与返回的数据集的数量相匹配。
在Node中,7行中的每一行只包含一个<unnamed portal 1>字符串。
connection.query("BEGIN");
connection.query({text: "SELECT getoperationaldatasetmodel($1)", values : [clientid]}, function(err, results) {
if (err) {
connection.query("COMMIT");
self.pool.release(connection);
callback(err);
}
else {
var opsDataset = null;
var rows = results.rows;
// this returns 7 rows but the rows do not contain data but rather the name of the dataset.
}那么: node-postgres是否支持多个结果集,如果支持,对如何提取有什么建议吗?
编辑:这是我在node-postgres中使用的代码,如果将来其他人需要使用它的话。
// must wrap in a transaction otherwise won't be able to see the multiple sets.
connection.query("BEGIN");
connection.query({text: "SELECT myfunction($1)", values : [clientid]}, function(err, results) {
if (err) {
// handle error here
connection.query("COMMIT;");
}
else {
connection.query('FETCH ALL FROM "<unnamed portal 1>"', function(err, r1) {
// r1.rows will contain the data for the first refcursor
});
connection.query('FETCH ALL FROM "<unnamed portal 2>"', function(err, r2) {
// r2.rows will contain the data for the second refcursor
});
// remember to handle the closure of the transaction
});发布于 2012-08-24 09:05:32
更新:有关如何获取和管理引用的解释,请参阅this excellent tutorial。
由于node-postgres无法识别您返回的引用作为结果集句柄,因此它似乎不支持来自PostgreSQL的多个结果集。这是很公平的,因为PostgreSQL实际上也不支持多个结果集,它们只是用引用来模拟。
您可以通过SQL级别的游标命令SQL-level cursor commands从refcursor执行FETCH操作,尽管它的文档非常糟糕。您不需要使用PL/PgSQL游标处理来完成此操作。只要:
FETCH ALL FROM "<unnamed portal 1>";请注意双引号,这一点很重要。将函数返回的refcursor名称替换为<unnamed portal 1>。
另请注意,除非创建了WITH HOLD游标,否则创建refcursor的事务必须仍处于打开状态。当事务提交或回滚时,非HOLD游标将被关闭。
例如,给定虚拟的refcursor返回函数:
CREATE OR REPLACE FUNCTION dummy_cursor_returning_fn() RETURNS SETOF refcursor AS $$
DECLARE
curs1 refcursor;
curs2 refcursor;
BEGIN
OPEN curs1 FOR SELECT generate_series(1,4);
OPEN curs2 FOR SELECT generate_series(5,8);
RETURN NEXT curs1;
RETURN NEXT curs2;
RETURN;
END;
$$ LANGUAGE 'plpgsql';..。它返回一组游标,您可以通过将门户名称传递给FETCH来获得结果,例如:
regress=# BEGIN;
BEGIN
regress=# SELECT dummy_cursor_returning_fn();
dummy_cursor_returning_fn
---------------------------
<unnamed portal 7>
<unnamed portal 8>
(2 rows)
regress=# FETCH ALL FROM "<unnamed portal 7>";
generate_series
-----------------
1
2
3
4
(4 rows)
regress=# FETCH ALL FROM "<unnamed portal 8>";
generate_series
-----------------
5
6
7
8
(4 rows)
regress=# https://stackoverflow.com/questions/12101773
复制相似问题