2017-08-03 143 views
0

所以我有一个函数select_id_from_table(_t)。它选择表格的某一列(_t),其中_t是表格名称作为参数。 我这样称呼它SELECT select_id_from_table('tablename')。现在我想在函数做这样的事情,以创建另一个功能:在postgresql更新函数中传递参数和参考

CREATE OR REPLACE FUNCTION myfunction(_u type1, _t type2) returns void as $$ 
BEGIN 
UPDATE (_u) set score=score+1 where _u.id in _t.id; 
END; 
$$ LANGUAGE plpgsql 

问题是,它不能正确传递参数。而且type1和type2应该是什么? _u和_t都是表格的名称。我曾尝试:

$$begin 
create temp table lid as (select * from select_id_from_table(_t)); 
execute format ('update '||quote_ident(_u) ||' set score= score+1 where 
'||quote_ident(_u) ||'.id_ in (
select * from select_id_from_table ('||quote_ident(_t)||') as 
abc)'); 
end;$$ 

我也尝试创建一个临时表中,选择select_id_from_table(_t)到该临时表,并利用它以后参考。但我仍然不知道如何在execute format('')中引用它。任何想法,将不胜感激。

回答

0

我假设select_id_from_table是返回SETOF <something>的函数,返回类型可以转换为text

我没有测试它,但我会做与此类似:

DECLARE 
    in_clause text; 
BEGIN 
    SELECT string_agg(quote_literal(t::text), ', ') INTO in_clause 
     FROM select_id_from_table(_u) s(t); 
    EXECUTE format ('UPDATE %I 
        SET score = score + 1 
        WHERE %I.id_ =ANY (' || in_clause || ')', 
        _u, _u); 
END; 
+0

我改变string_agg(T ::文 ''),并在%I.id_(.. )然后它工作。谢谢! –