Postgresql

函式執行查詢,操作結果,然後返回相同的結果

  • June 11, 2014

我需要一個執行類似虛擬碼的函式:

function get_data() RETURN SET OF something... as
BEGIN
   myResultSet = select id, some_other_column from ...... limit 20000;
   update some_other_table set status = 2 where id in (myResultSet.id);
   RETURN QUERY myResultSet;
END;

換句話說,我需要執行一個查詢,使用我在其他更新語句中獲得的 ID,然後返回相同的查詢結果。

我想知道是否有辦法將結果集儲存在某種變數中,但我的研究沒有找到任何好的結果。任何其他類型的解決方案都值得讚賞,因為我不需要兩次執行相同的查詢。

您可以使用游標。

create type my_type as (id int, other_column text);

create or replace function get_data ()
returns setof my_type
language plpgsql as $$
declare
   cur cursor for select id, other_column from my_table limit 20000;
   rec record;
begin
   for rec in cur loop
       update other_table
           set status = 2 
           where id = rec.id;
       return next rec;
   end loop;
end $$;

select * from get_data();

但請注意,該函式將執行 20000 次(可能更少)更新,而不僅僅是一次。性能會比一個查詢更好或更差並不明顯,因為它取決於各種情況。例如,一個查詢在空閒伺服器上應該快得多,而該函式在負載較重的伺服器上可能會更好。檢查它的最好方法是在實際環境中測試該功能。


您也可以使用臨時表。在這種情況下,行在一個查詢中更新。

create or replace function get_data_2 ()
returns setof my_type
language plpgsql as $$
begin
   create temporary table temp_table of my_type on commit drop;
   insert into temp_table
       select id, other_column from my_table limit 20000;
   update other_table 
       set status = 2
       where id in (select id from temp_table);
   return query select * from temp_table;
end $$;

引用自:https://dba.stackexchange.com/questions/67999