数据类型用于在plpgsql函数中选择并访问其字段

时间:2018-01-10 15:31:38

标签: postgresql plpgsql

我在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;

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

1 个答案:

答案 0 :(得分:2)

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

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

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;