在 Postgresql 中追加多行结果

Appending multiple row results in Postgresql

我想知道我是否在使用 postgreSQL 中的游标/函数连接多个值时遇到问题。

我有一个 table names Products,其中包含购买不同产品的客户的多个值,因此客户可以有多个条目。

因此,如果我将客户电子邮件作为参数,我的要求是获得 HTML 的一部分。

例如: 如果我给 ss@gmail.com 其中包含 table 中的两个条目,输出应该如下所示,

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

我认为您可以在不使用 CURSOR 的情况下尝试另一种解决方案,如下所示:

CREATE OR REPLACE FUNCTION append_products(cust_email TEXT)
RETURNS SETOF TEXT
AS $$
DECLARE
    html_script TEXT DEFAULT '<p style="line-height: 14px; text-align: center; font-size: 12px; margin: 0;"> ';
    rec_product RECORD;
BEGIN
    FOR rec_product IN
        SELECT "Name", "Product", "itemcount"
        FROM dl."Products"
        WHERE "email" = cust_email
    LOOP
        IF rec_product.itemcount > 0 THEN
            RETURN NEXT html_script || rec_Product."Product" || ' <\p>';
        END IF;
    END LOOP;
END;
$$  LANGUAGE PLPGSQL;

您可以查看示例 DBFiddle here

如果您不想要集合 returning 函数,这里是单个字符串 return 选项:

CREATE OR REPLACE FUNCTION append_products(cust_email TEXT)
RETURNS TEXT
AS $$
DECLARE
    html_script TEXT DEFAULT '<p style="line-height: 14px; text-align: center; font-size: 12px; margin: 0;"> ';
    rec_product RECORD;
    result TEXT DEFAULT '';
BEGIN
    FOR rec_product IN
        SELECT "Product"
        FROM "Products"
        WHERE "email" = cust_email
    LOOP
        result := result || html_script || rec_Product."Product" || ' <\p>';
    END LOOP;

    RETURN result;
END;
$$  LANGUAGE PLPGSQL;

有了新的 fiddle here.