Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psql - loop variable of loop over rows must be a record or row variable or list of scalar variables

Here is my simple anonymous code block:

do $$   declare foo varchar(50) := '';   begin     for a in       select a from (values('foo'), ('bar'), ('fooBar')) s(a)     loop       foo := a;       print foo;     end loop;   end; $$; 

When I run it:

psql -f test.sql 

I get this error:

psql:test.sql:11: ERROR:  loop variable of loop over rows must be a record or row variable or list of scalar variables LINE 4:     for a in             ^ 
like image 882
Richard Knop Avatar asked Apr 11 '13 12:04

Richard Knop


People also ask

How do you write a loop in PostgreSQL?

The syntax of the for loop statement to iterate over a result set of a dynamic query: [ <<label>> ] for row in execute query_expression [ using query_param [, ... ] ] loop statements end loop [ label ];

Can we use for loop in PostgreSQL?

In PostgreSQL, we can also use a for loop without creating a function. Instead, we will create an anonymous block and in the block, we will define a for loop. In the above code, first, we created an anonymous block and in the block, we created an array variable with some values.

What is record type variable in PSQL?

PostgreSQL uses record type variables which simply act as placeholders for rows of a result set, similar to a row type variable. However, unlike row type variables, they do not have a predefined structure. Their structure is only determined after assigning a row to them.

Which of the following is correct syntax to declare a variable in PL pgSQL?

The general syntax of a variable declaration is: name [ CONSTANT ] type [ COLLATE collation_name ] [ NOT NULL ] [ { DEFAULT | := | = } expression ];


1 Answers

Solved it myself, meh. Needed to declare arow record.

do $$   declare     arow record;     foo varchar(50);   begin     for arow in       select a from (values('foo'), ('bar'), ('fooBar')) s(a)     loop       foo := arow.a;       RAISE NOTICE 'Calling cs_create_job(%)', foo;     end loop;   end; $$; 
like image 156
Richard Knop Avatar answered Sep 18 '22 07:09

Richard Knop