plpgsql 函数中 select 的数据类型并访问其字段

Data Type for select in plpgsql function and access its fields

我在 Postgres 9.5 数据库中有以下表格:

product

 Column         |            Type             |                       Modifiers
----------------+-----------------------------+-----------------------------------------------------
id              | integer                     | not null default nextval('product_id_seq'::regclass)
name            | character varying(100)      |
number_of_items | integer                     |
created_at      | timestamp without time zone | default now()
updated_at      | timestamp without time zone | default now()
total_number    | integer                     |
provider_id     | integer                     |  
 Indexes:
    "pk_product" PRIMARY KEY, btree (id)
 Foreign-key constraints:
   "fk_product_provider" FOREIGN KEY (provider_id) REFERENCES provider(id)

我们还有

provider

     Column    |            Typ         |           Modifiers
  -------------+------------------------+------------------------------
   id          |       integer          | not null default nextval('property_id_seq'::regclass)
   name        |       text             |
   description |       text             |
   created_at  | timestamp without time zone | default now()
   updated_at  | timestamp without time zone | default now()
 Indexes:
      "pk_provider" PRIMARY KEY, btree (id)

我正在实现一个 plpgsql function,它应该找到 provider 的一些特定产品并循环遍历它们

      products = select u_id, number_of_items from product 
          where provider_id = p_id and total_number > limit;
      loop 
          //here I need to loop through the products 

      end loop;

问题 我应该为 products 变量声明什么样的 data type 以便将查询的产品存储到其中?以及我以后应该如何访问它的列,如 idnumber_of_items

在 PostgreSQL 中,创建 table 还定义了一个与 table 同名的复合数据类型。

您可以使用该类型的变量:

DECLARE
   p product;
BEGIN
   FOR p IN SELECT product FROM product WHERE ...
   LOOP
      [do something with "p.id" and "p.val"]
   END LOOP;
END;

或者您可以为您需要的各个字段使用多个变量(可能更好):

DECLARE
   v_id integer;
   v_val text;
BEGIN
   FOR v_id, v_val IN SELECT id, val FROM product WHERE ...
   LOOP
      [do something with "v_id" and "v_val"]
   END LOOP;
END;