1

I'm trying to use a FOR loop:

create or replace function update_revisions() returns trigger as 
$$ 
begin 
    declare col_name declare col_name information_schema.columns%ROWTYPE; 

    for col_name in
       select column_name from information_schema.columns
       where table_name='t'
    loop 
        insert into debug_table values (col_name); 
    end loop;
end;
$$
language plpgsql; 

But it always says:

syntax error at or near 'for'

Could someone please give me a hint what's wrong with it?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
BadIdeaException
  • 2,125
  • 15
  • 32
  • 2
    Declare section must be placed before `begin` keyword, not after, see general syntax here: http://www.postgresql.org/docs/9.3/static/plpgsql-structure.html and a few examples here: http://www.postgresql.org/docs/9.3/static/plpgsql-declarations.html – krokodilko Apr 02 '14 at 17:53
  • 1
    Why are you using a loop at all? The `INSERT INTO ... SELECT ...` form of INSERT should be sufficient. – mu is too short Apr 02 '14 at 17:54

1 Answers1

3

Immediate problem

Invalid syntax. Untangled:

create or replace function update_revisions()
  returns trigger as 
$$ 
declare
   col_name information_schema.columns%ROWTYPE; 
begin 
   for col_name in
      select column_name from information_schema.columns
      where table_name='t'
   loop 
      insert into debug_table values (col_name); 
    end loop;
end;
$$  language plpgsql;

More problems

  • Table names are not unique in a Postgres database. More in this recent answer:
    Behaviour of NOT LIKE with NULL values

  • The whole approach is inefficient. Use a single INSERT statement instead:

INSERT INTO debug_table (target_column)  -- with column definition list!
SELECT column_name
FROM   information_schema.columns
WHERE  table_name = 't'
AND    table_schema = 'public';          -- your schema
Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • Thanks, it works now. I'll look into the non-unique table names. The insert statement is just there for debugging purposes, not the actual production code. – BadIdeaException Apr 02 '14 at 19:19