如何返回postgresql函数中删除的行数

时间:2017-12-17 16:31:17

标签: postgresql

这是我想要做的一个非常简化的例子。考虑一下这个人的表:

CREATE TABLE people (pid SERIAL PRIMARY KEY, firstname TEXT, isalive BOOLEAN);

INSERT INTO people (firstname, isalive) VALUES
    ('Sam', TRUE),
    ('Leslie', FALSE),
    ('Parker', FALSE);

现在我想从表中删除死人。当我在psql中执行此操作时,会看到一条消息,告诉我删除了多少行。

postgres=> DELETE FROM people WHERE isalive = FALSE;
DELETE 2
postgres=>

但是,如果我将此删除语句放入函数并调用它,我看不到相同的消息。

CREATE OR REPLACE FUNCTION deletedead() RETURNS void AS $$
  DELETE FROM people WHERE isalive = FALSE;
$$ LANGUAGE SQL;

SELECT deletedead();

这会按预期删除行,但不会显示任何消息,说明删除了多少行。 如何从此功能中获取“DELETE 2”等消息?

我尝试修改我的函数以返回已删除的行数:

-- This doesn't work
CREATE OR REPLACE FUNCTION deletedead() RETURNS int AS $$
  DELETE FROM people WHERE isalive = FALSE RETURNING COUNT(*);
$$ LANGUAGE SQL;

...但我收到错误ERROR: aggregate functions are not allowed in RETURNING

1 个答案:

答案 0 :(得分:2)

错误消息是正确的。你应该能够做到:

CREATE OR REPLACE FUNCTION deletedead() RETURNS bigint AS $$
  WITH d as (
        DELETE FROM people WHERE isalive = FALSE RETURNING *
       )
  SELECT COUNT(*)
  FROM d;
$$ LANGUAGE SQL;