How to pass a record to a PL/pgSQL function?

前端 未结 3 591
醉酒成梦
醉酒成梦 2021-01-04 23:43

I have 8 similar PL/pgSQL functions; they are used as INSTEAD OF INSERT/UPDATE/DELETE triggers on views to make them writable. The views each combine columns of

3条回答
  •  悲&欢浪女
    2021-01-05 00:23

    Basically you can convert a record to a hstore variable and pass the hstore variable instead of a record variable to a function. You convert record to hstore i.e. so:

    DECLARE r record; h hstore;
    h = hstore(r);
    

    Your helper function should also be changed so:

    CREATE FUNCTION insert_thing (new_thing hstore) RETURNS INTEGER AS $fun$
    DECLARE
        inserted_id  INT;
    BEGIN
        INSERT INTO things (name) VALUES (
            new_thing -> 'name'
            -- (plus 30 more columns)
        ) RETURNING id INTO inserted_id;
        RETURN inserted_id;
    END;
    $fun$ LANGUAGE plpgsql;
    

    And the call:

    inserted_id = insert_thing(hstore(NEW));
    

    hope it helps

提交回复
热议问题