0

因此,我正在尝试创建一个过程,该过程将在我的表中查找特定行,将该行保存在要返回的结果中,删除该行,然后返回结果。

我设法做的最好的事情是:

CREATE OR REPLACE FUNCTION sth(foo integer)
RETURNS TABLE(a integer, b integer, ... other fields) AS $$
DECLARE
    to_delete_id integer;
BEGIN
    SELECT id INTO to_delete_id FROM my_table WHERE sth_id = foo LIMIT 1;
    RETURN QUERY SELECT * FROM my_table WHERE sth_id = foo LIMIT 1;

    DELETE FROM my_table where id = to_delete_id;
END;
$$ LANGUAGE plpgsql;

如您所见,我有 2 个SELECT操作几乎做同样的事情(额外开销)。有没有办法只拥有第二个SELECT并设置,to_delete_id 以便之后我可以删除该行?

4

3 回答 3

6

你只想要一个DELETE...RETURNING

DELETE FROM my_table WHERE sth_id=foo LIMIT 1 RETURNING *

Edit based on ahwnn's comment. Quite right too - teach me to cut + paste the query without reading it properly.

DELETE FROM my_table WHERE id = (SELECT id ... LIMIT 1) RETURNING *
于 2013-10-04T11:39:32.380 回答
1

Can be done much easier:

CREATE OR REPLACE FUNCTION sth(foo integer)
RETURNS SETOF my_table
AS
$$
BEGIN
    return query
      DELETE FROM my_table p
      where sth_id = foo
      returning *;
END;
$$ 
LANGUAGE plpgsql;
于 2013-10-04T11:47:09.280 回答
0

将所有列选择为变量,返回它们,然后使用 id 删除:

为每列声明一个变量(按照约定命名为保存为列但带有前导下划线),然后:

SELECT id, col1, col2, ...
INTO _id, _col1, _col22, ...
FROM my_table
WHERE sth_id = foo
LIMIT 1;

RETURN QUERY SELECT _id, _col1, _col22, ...;

DELETE FROM my_table where id = _id;
于 2013-10-04T11:36:50.717 回答