Обсуждение: plpgsql question: inserting records

Поиск
Список
Период
Сортировка

plpgsql question: inserting records

От
Brian Hurt
Дата:
There has to be an easy way to do this and I'm just being stupid and
missing it.  What I want to do is, in plpgsql, insert a record (of the
right type) into a table without having to list all the columns of the
table.  For example, I'd like to do:

CREATE FUNCTION example(id_to_copy INTEGER) RETURNS VOID AS $_$
DECLARE
    t_rec RECORD;
BEGIN
    FOR t_rec IN
        SELECT
            *
        FROM
            table_with_lots_of_columns
        WHERE
            unique_id = id_to_copy
    IN
        t_rec.unique_id := new_unique_id();
        INSERT INTO table_with_lots_of_columns VALUES t_rec; -- or something
    END LOOP;
END
$_$ LANGUAGE plpgsql;

Now, I can do this by listing all the columns from the table, but this
is annoying.  Is there a way to do this cleaner?


Thanks,
Brian


Re: plpgsql question: inserting records

От
Tom Lane
Дата:
Brian Hurt <bhurt@janestcapital.com> writes:
> There has to be an easy way to do this and I'm just being stupid and
> missing it.  What I want to do is, in plpgsql, insert a record (of the
> right type) into a table without having to list all the columns of the
> table.  For example, I'd like to do:

Some experimentation says that "VALUES(t_rec.*)" will work as long as
t_rec is declared as the table's rowtype, and not generic "record".
(I didn't try it further back than 8.1 though.)

For future-proofing purposes I'd advise spelling it with extra
parentheses: VALUES((t_rec).*).  It doesn't matter right now but
might someday.

            regards, tom lane