Postgresql嵌套的Foreach Int数组

时间:2017-12-11 10:18:49

标签: sql postgresql

我想要做的是,声明两个数组。 一个用于发票阵列包含发票ID和发票的债务,(例如[6238,236.0000]) 另一个是客户以前的收到的收藏品。(例如客户有3个收藏[62.000,40.000,10.000])

我的桌子就像这些。

  • 发票付款(包含特定发票和客户的所有付款)

    总数(18,4)
    InvoiceId整数
    描述字符变化
    ClientId整数
    ...
    其他一些值也不重要。


  • 发票

    InvoiceId整数
    grandtotal数字(18,4)
    ClientId整数
    InvoiceDate日期

    ...
    其他一些值也不重要。

  • 客户移动

    ClientId整数
    CreatedDate Date
    将数字(18,4)

    ...
    其他一些值也不重要。

我尝试在PostgreSQL中使用嵌套的Foreach语句创建一个函数。实际上,这将是插入,更新,删除功能之后的触发器。

出于测试目的,我现在写一个函数。所以我手动获取_clientid和_clientmoveid。

 CREATE FUNCTION invoice_pay(_clientid int,_clientmoveid int) RETURNS int[]  AS $$
DECLARE _invoices varchar[] := (select  array_agg(DISTINCT '[' || inv.invoiceid || ',' || CAST (inv.grandtotal AS int) || ']') from invoices inv 
left join invoicepayments as ip on inv.invoiceid = ip.invoiceid where inv.clientid = _clientid group by inv.invoiceid,inv.grandtotal order by inv.invoicedate);
DECLARE _collections varchar[] := (SELECT array_agg(DISTINCT '[' || clm.will || ']') from clientmovements clm where clm.clientid = _clientid
 group by clm.createddate order by clm.createddate desc);


DECLARE _total numeric(18,4);
DECLARE _collectionTotal int;
DECLARE _invoicesArray int[];
BEGIN

/*first delete all the previous payments*/
DELETE FROM InvoicePayments where clientid = _clientid;



/*loop through all invoices and those remaining payments */
   /*first array contains invoiceid and invoicegrandtotal [6232,246.0000]*/
    FOREACH _invoicesArray SLICE 1 IN ARRAY _invoices
    LOOP
    /*loop throught all collections that client had. The second array contains only collections from client. [[15],[20],[40]]*/
           FOREACH _collectionTotal IN ARRAY _collections
           LOOP
            /*the total calculation is the if collection is bigger than the invoice grandtotal, close invoice as paid. Other than grandtotal minus collection*/
           _total := (case when _collectionsTotal > _invoicesArray[2] then _collectionsTotal else _invoicesArray[2] - collectionsTotal end);
            insert into invoicepayments(total,description,clientid,invoiceid)
    values(_total,'test',_clientid,_invoicesArray[1]);
           END LOOP;
    END LOOP;

RETURN _invoices;
END;
$$ LANGUAGE plpgsql;

在那个函数之后,我得到一个错误  整数的无效输入语法:" {6328,236.0000}" 可能在某些时候,我的阵列的第一个或第二个值不像我想的那样有效。我像_invoicesArray [1]那样使用它们。我想从_invoicesArray [1]值中取6328,但它给了我一个错误。我应该怎样做嵌套的foreach,我该怎么办?

0 个答案:

没有答案