简体   繁体   中英

How to ARRAY values from a SELECT query in POSTGRES

I am trying to structure an array within my postgres call by pulling 3 values (all SMALLINT's) from a table and turning them into an array so that I can use them in the rest of the call like so code_list[0] .

Currently, I have only created this part of the function so that I can ensure that I am structuring it correctly before I proceed. However, I receive this error error: subquery must return only one column which makes me thing that it assume that I am trying to return a TABLE. I can't save a table in into one value as far as I am aware so I am trying to create an array instead.

Am I creating an ARRAY properly? Is there a way to transform this into JSONB if that would be a better strategy?

CREATE OR REPLACE FUNCTION "RetrieveCodeValues" (
  "@code"        VARCHAR(50)
)
RETURNS SMALLINT[] AS
$func$
BEGIN      
  SELECT ARRAY (
    SELECT c."big", c."mid", c."small"
    FROM "codes" AS c
    WHERE "code" = "@code"
  ) AS code_list;
  RETURN code_list;
END;
$func$ LANGUAGE PLPGSQL;

Use the array constructor:

DECLARE res integer[];
BEGIN
   SELECT ARRAY[c.big, c.mid, c.small] INTO res
   FROM ...
   RETURN res;
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM