Re: looping through query to update column

From: "Albe Laurenz" <all(at)adv(dot)magwien(dot)gv(dot)at>
To: <pgsql-general(at)postgresql(dot)org>
Subject: Re: looping through query to update column
Date: 2006-10-13 07:23:29
Message-ID: 52EF20B2E3209443BC37736D00C3C1380AD6067E@EXADV1.host.magwien.gv.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Jean-Christophe Roux wrote:
> I am trying to loop through a table to update one column
>
> create or replace function foo() returns integer as $$
> declare
> rec RECORD;
> row integer := 0;
> begin
> for rec in select * from table loop
> update rec set recordid = row;
> row++;
> end loop;
> return 0;
> end;
> $$ language plpgsql
>
> In pgadmin, I am getting the following error message, but
> that does not help me much:
> ERROR: syntax error at or near "$1" at character 9
> QUERY: update $1 set recordid = $2
> CONTEXT: SQL statement in PL/PgSQL function "foo" near line 6

You cannot UPDATE a record, you can only UPDATE a table.

So it should be something like
UPDATE table SET recordid = row WHERE primarykey = rec.primarykey

You might use 'ctid' to identify the row if you have no suitable
primary key (you do have one, don't you?), but beware that ctid
can change suddenly and unexpectedly when somebody else modifies
the row. To protect against that, you can either LOCK the table or
SELECT ... FOR UPDATE.

Yours,
Laurenz Albe

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Martijn van Oosterhout 2006-10-13 07:50:04 Re: UTF-8
Previous Message Peter 2006-10-13 06:10:38 Re: Override system-defined cast?