gpt4 book ai didi

postgresql - plpgsql 函数中选择的数据类型并访问其字段

转载 作者:行者123 更新时间:2023-11-29 14:33:37 24 4
gpt4 key购买 nike

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

产品

 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)

我们还有

提供者

     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 函数,它应该找到 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 变量声明哪种数据类型,以便将查询的产品存储到其中?以及我以后应该如何访问它的列,如 idnumber_of_items

最佳答案

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

关于postgresql - plpgsql 函数中选择的数据类型并访问其字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48190866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com