PostgreSQL - 如何从select创建一个整数数组作为参数传递给函数

时间:2016-03-31 16:45:27

标签: sql arrays postgresql

我有一个函数接收integer[]数组作为参数。

CREATE OR REPLACE FUNCTION public.get_master_products(P_PRODUCTS_IDS integer[])
  RETURNS SETOF record
  LANGUAGE plpgsql
AS
$body$
DECLARE
    CURRENT_ID integer;
    PRODUCT RECORD;
    COMPONENT1 RECORD;
    COMPONENT2 RECORD;
    COMPONENT3 RECORD;
BEGIN
....

END;

当我调用此函数时,我必须这样做:

SELECT
    "ID",
    "CODE",
    "CODE2",
    "NAME",
    "COMPOSERS",
    "PTYPE_ID",
    "PTYPE_NAME",
    "COMPONENT_QUANTITY",
    "UM_ID",
    "LEVEL"
FROM 
    get_master_products(array[ 20, 40, 50, 80])
AS
    (
      "ID" integer,
      "CODE" varchar,
      "CODE2" varchar,
      "NAME" varchar,
      "COMPOSERS" numeric,
      "PTYPE_ID" bigint,
      "PTYPE_NAME" varchar,
      "COMPONENT_QUANTITY" numeric,
      "UM_ID" varchar,
      "LEVEL" varchar
    );

但有没有办法做这样的事情来调用函数?:

get_master_products(array[ (SELECT id, FROM products WHERE composers > 0) ])

使用SQL查询自动创建传递数组??

你能帮帮我吗?

谢谢

1 个答案:

答案 0 :(得分:0)

使用array_agg

get_master_products(SELECT array_agg(id) FROM products WHERE composers > 0)