在Postgresql中追加多行结果

问题描述 投票:-1回答:1

我有一个问题,我是否在使用postgreSQL中的Cursor / Function连接多个值时遇到问题。

我有一个表名称产品,其中包含几个购买不同产品的客户的价值,因此可以为客户提供多个条目。

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

例如:如果我给[email protected]包含表中的两个条目,输出应该如下所示,

<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;
sql postgresql function database-cursor
1个回答
1
投票

我认为你可以尝试不使用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

如果你不想在这里设置返回函数是一个单字符串返回选项:

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;

随着一个新的小提琴here

© www.soinside.com 2019 - 2024. All rights reserved.