0

I know the right way to insert value from a table:
insert into city (pop) select pop+2 from city
I just want to know how cursor works in Pl/pgsql .

I wish to use cursor in loop to insert some value:

create or replace function test(  ) returns void as 
$$
declare
cur cursor for select pop+2 from city order by pop;
b int;
row record;
begin
for row in cur
LOOP 
fetch cur into b;
insert into city(pop) select b;
end loop;
end;
$$ language plpgsql    

However, when I type select test() and the result table is:

enter image description here

It's very strange that only two rows are inserted. So I want to know what lead to this result?

Update my question in 04/05/2016:
I revise the function like this:

create or replace function test(  ) returns void as 
$$
declare
cur cursor for select * from city order by pop;
b record;
begin
for b in cur
LOOP 
insert into city(pop) select b.pop+2;
RAISE NOTICE ' % IS INSERTED' , b;
end loop;
end;
$$ language plpgsql

Then I get the correct result:
enter image description here

But I still wonder why in the first function, only two rows are inserted.

2
  • Why are you using a (slow and inefficient) cursor for this in the first place? You can do this much more efficiently using a single statement: insert into city (pop) select pop+2 from city;. Commented May 3, 2016 at 14:38
  • 1
    Just a guess: there are two fetches in the your loop: first, implicit, at for row in cur LOOP and second, explicit, at fetch cur into b;. So at each iteration you are doing actually two fetches. Commented May 3, 2016 at 15:10

1 Answer 1

1

I finally figure out that why the result is wrong, just like Abelisto's comment . I did two fetchers in loop at each step:

  1. at for row in cur LOOP ,
  2. at fetch cur into b

So the first row where pop=500 and the third row where pop =1000 have already been fetched in for loop, and it can't be fetched by b.

Sign up to request clarification or add additional context in comments.

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.