如何执行 PostgreSQL 'get diagnostics'

How to execute PostgreSQL 'get diagnostics'

PostgreSQL 9.3 手册描述了这个命令

'GET DIAGNOSTICS int_var = ROW_COUNT;' 

从上一个 insert/update 命令中获取受影响的行数。 当我在 GUI(pgAdmin 3,SQL 编辑器窗格)和 Python(使用 psycopg2 包)中尝试此操作时,我收到此错误:

ERROR: syntax error at or near "GET".

我做错了什么?

GET DIAGNOSTICS 只能在 plpgsql 函数中使用。您不能将其作为常规 sql 命令执行。请参阅以下简单示例:

create table fruits as
select * from (values
    (1, 'banana'),
    (2, 'pear'),
    (3, 'apple')) f(id, fruit);

create function update_fruits()
returns setof fruits language plpgsql
as $$
declare
    n int;
begin
    update fruits set id = id+ 1;
    get diagnostics n = row_count;
    return query select null::int, format ('%s rows updated', n);
    return query select * from fruits order by 1;
    get diagnostics n = row_count;
    return query select null::int, format ('%s rows retrieved', n);
end $$;

select * from update_fruits()

 id |      fruit
----+------------------
    | 3 rows updated
  2 | banana
  3 | pear
  4 | apple
    | 3 rows retrieved
(5 rows)    

它是后端功能,不是 SQL 语言的一部分。 Psycopg2 的 cursor.rowcount 属性包含此值。 Libpq C/C++ 库具有 PQcmdTuples 函数。