Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute WHILE LOOP in SQL (PostgreSQL/pgAdmin 4)?

I am trying to run this simple WHILE loop in pgAdmin’s query tool:

DECLARE @counter INT = 1;

WHILE @counter <= 5
BEGIN
    PRINT @counter;
    SET @counter = @counter + 1;
END

The desired result is just a list from 1 to 5, but my pgAdmin is returning this error:
*ERROR: syntax error at or near "@"
LINE 1: DECLARE @counter INT = 1;

I’m an undergrad in a non-IT course, so I hope you consider this in your explanations. Thank you!
(code source)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your example is from SQL Server, not PostgreSQL. You should try something like this:

do $$
declare 
   counter integer := 0;
begin
   while counter < 5 loop
      raise notice 'Counter %', counter;
      counter := counter + 1;
   end loop;
end$$;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading