代码之家  ›  专栏  ›  技术社区  ›  luffyx

在postgresql的更新函数中传递参数和引用

  •  1
  • luffyx  · 技术社区  · 8 年前

    所以我有一个函数 select_id_from_table(_t) 。它选择表(\u t)的某一列,其中\u t是表名作为参数。 SELECT select_id_from_table('tablename')

    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 
    

    $$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;$$
    

    我还尝试创建一个临时表,选择 并在以后引用它。但我还是不知道怎么引用 execute format('') 。如有任何想法,将不胜感激。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Laurenz Albe    8 年前

    我认为 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;