Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any shortcut to declare several variables of the same type in plpgsql?

Currently I declare all variables this way:

declare
  x int;
  y int;
  z int;
begin
  ...
end

Is it possible to declare x, y and z (which have the same type) in one line like:

declare
  x, y, z int;
begin
  ...
end

I've not found any hints in the documentation so far ...

like image 858
overdawn Avatar asked Mar 13 '23 10:03

overdawn


1 Answers

There is no syntax shortcut of the sort.

There is barely a need for this since PL/pgSQL is not meant to require lots of variables. An excessive number of variables would indicate an abuse of the language, which is best used as glue for SQL statements.

To declare a couple of variables of the same type, you can declare the first explicitly and copy the type for the rest with variable%TYPE. See:

DO
$func$
DECLARE
   x int;
   y x%TYPE;
   z x%TYPE;
BEGIN
   RAISE NOTICE 'type of x: %; type of y: %; type of z: %'
              , pg_typeof(x), pg_typeof(y), pg_typeof(z);
END
$func$

If your question is about in one line (I don't think so), you can do that, but each with its type:

   x int; y int; z int;

Or you can use an array type to hold any number of the same type, or a row or record type for any types ...

like image 152
Erwin Brandstetter Avatar answered Apr 06 '23 16:04

Erwin Brandstetter