2015-01-07 27 views
0

我是絕對的noob,找不到這個答案。
如何將結果添加到臨時表中?
也許你們對我有改善我的代碼的一些提示?在臨時表中保存遊標

我在這裏用遊標在結果中創建了一個函數。但我需要:

drop function if exists non_married_presidents(); 
create or replace function non_married_presidents() 
returns varchar as $$ 
declare 
    c_emp cursor for 
     select name, birth_year from president 
     where id not in(select pres_id from pres_marriage); 
begin 


    for emp in c_emp loop 
     raise notice 'name: %, birth_year: %', emp.name, emp.birth_year; 
    end loop; 
end; 
$$language plpgsql; 

電話:

select non_married_presidents(); 

回答

0

你問:

如何添加結果到臨時表?

您可能會反思這一點。只需使用CREATE TEMP TABLE AS ...

CREATE TEMP TABLE tmp_tbl AS 
-- INSERT INTO tmp_tbl (name, birth_year) -- or insert into existing table 
SELECT name, birth_year FROM president p 
WHERE NOT EXISTS (SELECT 1 FROM pres_marriage WHERE pres_id = p.id); 

您不需要遊標。這是一種罕見的情況,顯式遊標將是plpgsql中的最佳選擇。

雖然是在它,NOT IN是最好避免的構建體: