【发布时间】:2019-04-23 12:16:52
【问题描述】:
我在使用 postgreSQL 中的游标/函数连接多个值时遇到问题。
我有一个名为 Products 的表,其中包含购买不同产品的客户的多个值,因此客户可以有多个条目。
因此,如果我将客户电子邮件作为参数,我的要求是获取 HTML 的一部分。
例如: 如果我给 ss@gmail.com 其中包含表中的两个条目,则输出应如下所示,
<p style="line-height: 14px; text-
align: center; font-size: 12px; margin: 0;"> product 1 </p>
<p style="line-height: 14px; text-
align: center; font-size: 12px; margin: 0;"> product 2 </p>
但现在我只获得了一种产品的详细信息,就像这样, 产品 1
CREATE OR REPLACE FUNCTION
Append_Products(Customer_Email TEXT)
RETURNS text AS $$
DECLARE
rowcount BIGINT;
Products TEXT DEFAULT '';
HTMLscript TEXT DEFAULT '<p style="line-height: 14px; text-
align: center; font-size: 12px; margin: 0;">';
rec_Product RECORD;
cur_AppendProducts CURSOR(Customer_Email TEXT)
FOR SELECT "Name", "Product","itemcount"
FROM dl."Products"
WHERE "email" = Customer_Email;
BEGIN
-- Open the cursor
OPEN cur_Appendproducts(Customer_Email);
LOOP
-- fetch row into the film
FETCH cur_Appendproducts INTO rec_Product;
-- exit when no more row to fetch
EXIT WHEN NOT FOUND;
-- build the output
IF rec_Product.itemcount > 0 THEN
Products := HTMLscript || rec_Product."Product" || '</p>';
END IF;
END LOOP;
-- Close the cursor
CLOSE cur_Appendproducts;
RETURN Products;
END; $$ LANGUAGE plpgsql;
【问题讨论】:
-
是否有强制您使用光标的规定?这看起来可以通过
FOR循环来完成。看起来你也很想RETURN SETOF text。
标签: sql postgresql function database-cursor