5

I have written a PL/PgSQL trigger and i need to save the query (in fact the result set) to variable. See below:

DECLARE
    __query record;
    r record;
BEGIN
    __query := (SELECT * FROM posts);
    FOR r IN __query LOOP
        -- do something with the row data
    END LOOP;

    RETURN NEW;
END;

Which data type for query itself should i use?

I guess record is not appropriate data type and should be used in the loop cycle itself (for r var).

1
  • i believe you should use cursor here Commented Apr 19, 2011 at 12:11

3 Answers 3

3

If you mean you want to pass the query for the loop as a character variable, then you can do it like this:

DECLARE 
    _query : text;
    r : record;
BEGIN
    _query := 'SELECT * FROM posts';

    FOR r IN EXECUTE _query LOOP
       -- do stuff
    END LOOP;

    RETURN new;
END;
Sign up to request clarification or add additional context in comments.

Comments

3
DECLARE

  CURSOR cursor is (select * from posts);
  r      record;
BEGIN

FOR cursor_rec in cursor LOOP
  ... 
END LOOP;

Comments

-1
DECLARE

  cursor c is select * from posts;
  -- r  record; you don't need to declare this variable
BEGIN
   FOR c_rec in c LOOP
       ... 
       ... 
       ... 
   END LOOP;
END;

this code for oracle pl-sql

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.