1
create or replace function demowhile_()
    returns table (id integer,name varchar(50))
        language 'plpgsql'
       as $$

    declare id integer;
    declare name varchar(50);

    begin
    CREATE temporary TABLE demo_(id integer,name varchar(50));
    CREATE temporary TABLE temp_ (id integer);
        insert into temp_ (select id from demo);

            while (select count(*) from temp_) <> 0
            loop
                id = (select top(1) id from temp_);
                name = (select name from demo where id = id);
                insert into demo_ values (id,name);

                delete from temp_ where id = id;

                end loop;

                return query select id,name from demo;
                end;
                $$;

****while executing it is giving error like ****

select * from demowhile();

**ERROR:  column reference "id" is ambiguous
LINE 1: insert into temp_ (select id,name from demo)
                                  ^
DETAIL:  It could refer to either a PL/pgSQL variable or a table column.
QUERY:  insert into temp_ (select id,name from demo)
CONTEXT:  PL/pgSQL function demowhile() line 9 at SQL statement
SQL state: 42702**
3
  • 1
    just rename your variable id = (select top(1) id from temp_); to for example _id on all places where you actually want to use it Commented Feb 22, 2019 at 12:44
  • select top(1) is invalid for Postgres to begin with Commented Feb 22, 2019 at 13:18
  • 1
    The whole approach seems unnecessarily complicated. As far as I can tell this could be done with one simple SQL statement. No loops, not "top", not PL/pgSQL - especially because at the end you just return the contents of the demo table that wasn't changed by the inefficient and slow row-by-row processing in the loop. What is the real problem are you trying to solve with that? Commented Feb 22, 2019 at 13:22

1 Answer 1

1

demowhile_() returns table (id integer,name varchar(50) is basically the same thing as demowhile_(out id integer, out name varchar(50)) returns setof record

The id output column can be referenced directly from within the function. You've then also created a function variable named id. So when you assign a value to id, are you assigning to the output parameter or the declared variable? PG doesn't know, so you get that error.

And of course the simple solution is to give each a unique name.

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.