Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PL/pgSQL SELECT into an array

Here's my function declaration and part of the body:

CREATE OR REPLACE FUNCTION access_update()
RETURNS void AS $$
DECLARE team_ids bigint[];
BEGIN
    SELECT INTO team_ids "team_id" FROM "tmp_team_list";

    UPDATE "team_prsnl"
    SET "updt_dt_tm" = NOW(), "last_access_dt_tm" = NOW()
    WHERE "team_id" IN team_ids;
END; $$ LANGUAGE plpgsql;

I want team_ids to be an array of ints that I can then use in the UPDATE statement. This function give me errors like this:

psql:functions.sql:62: ERROR:  syntax error at or near "team_ids"
LINE 13:  AND "team_id" IN team_ids;
like image 727
nnyby Avatar asked Jul 31 '12 00:07

nnyby


People also ask

How do I select an array in PostgreSQL?

PostgreSQL allows us to define a table column as an array type. The array must be of a valid data type such as integer, character, or user-defined types. To insert values into an array column, we use the ARRAY constructor.

What is [] in PostgreSQL?

Array Type. PostgreSQL gives the opportunity to define a column of a table as a variable length single or multidimensional array. Arrays of any built-in or user-defined base type, enum type, or composite type can be created. We will focus on one data type in particular, the Array of text, text[].

How do I create an array in PostgreSQL?

To create a column of an array type, the [] symbol is used. The following examples illustrate this: create table contacts ( first_name varchar, last_name varchar, phone_numbers varchar[] ); create table player_scores ( player_number integer, round_scores integer[] );

How do I assign a selection to a variable in PostgreSQL?

In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.


1 Answers

Faster and simpler with a FROM clause in your UPDATE statement:

UPDATE team_prsnl p
SET    updt_dt_tm = now()
      ,last_access_dt_tm = now()
FROM   tmp_team_list t
WHERE  p.team_id = t.team_id;

That aside, while operating with an array, the WHERE clause would have to be

WHERE team_id = ANY (team_ids)

The IN construct works with sets, not with arrays.

like image 102
Erwin Brandstetter Avatar answered Oct 14 '22 04:10

Erwin Brandstetter