Create a function declaring a predefined text array

Edson Horacio Junior picture Edson Horacio Junior · Jul 24, 2014 · Viewed 22.8k times · Source

I need to create a function in Postgres and one of the variables I declare is a predefined text array, but I don't know the syntax to set its values. This is what I have so far:

CREATE OR REPLACE FUNCTION testFunction() RETURNS text
AS $$
DECLARE
    TESTARRAY TEXT['value 1', 'value 2', 'value 3'];
BEGIN
    return 'any text';
END;
$$ LANGUAGE 'plpgsql';

I get this error when I execute the code:

ERROR:  syntax error at or near "'value 1'"
LINE 5: TESTARRAY TEXT['value 1', 'value 2', 'value 3'];

Answer

pozs picture pozs · Jul 24, 2014

The right syntax for default value (in a variable declaration) is { DEFAULT | := } expression.

For expression, you can use any of the array inputs.

F.ex. these can work:

DECLARE
  test1  TEXT ARRAY  DEFAULT  ARRAY['value 1', 'value 2', 'value 3'];
  test2  TEXT[]      :=       '{"value 1", "value 2", "value 3"}';
  test3  TEXT[]      DEFAULT  ARRAY[]::TEXT[]; -- empty array-constructors need a cast