如何执行PostgreSQL'获取诊断'

Ami*_*atz 2 sql postgresql plpgsql

PostgreSQL 9.3手册描述了这个命令

'GET DIAGNOSTICS int_var = ROW_COUNT;' 
Run Code Online (Sandbox Code Playgroud)

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

ERROR: syntax error at or near "GET".
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

kli*_*lin 8

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)    
Run Code Online (Sandbox Code Playgroud)


Tom*_*rta 4

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