Question

I was trying to make a basic for loop sample. Couldn't find what I did wrong. Can you please help:

BEGIN
    FOR i_ IN 1..100 LOOP
        INSERT INTO "MYSHM".aaa values (i_,i_ + 1 ,i_ + 2,i_ + 3);
    END LOOP;
END

[ERROR ] 2.0-2: syntax error, unexpected character

Was it helpful?

Solution

Procedural code is only allowed inside a DO statement or a function body.
Using the default procedural language PL/pgSQL (but there are many other options):

DO
$do$
BEGIN
   FOR i IN 1..100 LOOP
      INSERT INTO "MYSHM".aaa   -- column definition list ?!
      VALUES (i, i + 1, i + 2, i + 3);
   END LOOP;
END
$do$;

Or, better, recast your problem as set-based operation with generate_series():

INSERT INTO "MYSHM".aaa         -- column definition list ?!
SELECT i, i + 1, i + 2, i + 3
FROM   generate_series(1,100) i;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top