Iterate over query

时间:2016-08-31 12:28:50

标签: postgresql plpgsql

I am trying to iterate over a query that I just generated and execute triggers bit it seems Postgres doesn't recognize what I want to do,how can I fix it?

   CREATE OR REPLACE FUNCTION get_all_rezultz() RETURNS VOID AS
   $BODY$

    BEGIN
 FOR r IN (SELECT 'CREATE TRIGGER ' || tab_name|| '_if_modified_trg AFTER INSERT OR UPDATE OR DELETE ON ' || tab_name|| ' FOR EACH ROW EXECUTE PROCEDURE audit.if_modified_func(); ' AS trigger_creation_query
FROM (
SELECT  quote_ident(table_name) as tab_name
    FROM information_schema.tables
    WHERE table_schema='public'

    )  AS foo WHERE tab_name||'_if_modified_trg' NOT IN (SELECT tgname from pg_trigger where not tgisinternal))

LOOP

    -- can do some processing here
 EXECUTE r.trigger_creation_query;
END LOOP;
RETURN;
  END
 $BODY$
LANGUAGE plpgsql;

I get the error - ERROR: loop variable of loop over rows must be a record or row variable or list of scalar variables

1 个答案:

答案 0 :(得分:0)

 CREATE OR REPLACE FUNCTION get_all_rezultz() RETURNS VOID AS
   $BODY$
    DECLARE
    r RECORD;
    BEGIN
 FOR r IN (SELECT 'CREATE TRIGGER ' || tab_name|| '_if_modified_trg AFTER INSERT OR UPDATE OR DELETE ON ' || tab_name|| ' FOR EACH ROW EXECUTE PROCEDURE audit.if_modified_func(); ' AS trigger_creation_query
FROM (
SELECT  quote_ident(table_name) as tab_name
    FROM information_schema.tables
    WHERE table_schema='public'

    )  AS foo WHERE tab_name||'_if_modified_trg' NOT IN (SELECT tgname from pg_trigger where not tgisinternal))

LOOP

    -- can do some processing here
 EXECUTE r.trigger_creation_query;
END LOOP;
RETURN;
  END
 $BODY$
LANGUAGE plpgsql;