简体   繁体   中英

Postgres,functions,before insert vladate arrays values

This is my function `

create or replace function test.insert(_orderid integer, __partnerids      
integer[], __maginitude double precision[])
returns boolean
language plpgsql
as $$
DECLARE  res boolean;
BEGIN
PERFORM orderid
FROM test.order_partner_magnitude
WHERE orderid = _orderid
FOR UPDATE SKIP LOCKED;

DELETE
FROM test.order_partner_magnitude
WHERE orderid = _orderId;

INSERT INTO test.order_partner_magnitude(orderid, partnerid, magnitude)
SELECT _orderId, unnest(__partnerids),unnest(__maginitude);

res =true ;
RETURN res;
end ;
$$;

Some using example SELECT test.insert(1, '{30,10,20}','{46,59,12}'); result will be

orderid | partnerid | magnitude
      1 |        30 |        46
      1 |        10 |        59
      1 |        20 |        12

now I need to check is parter busy,I can get busy partners id with this query SELECT partnerid from test.order_partner WHERE status = 1 ;

Example partner with id 20 is busy after insert result must be `

orderid | partnerid | magnitude
      1 |        30 |        46
      1 |        10 |        59

I want to insert all data with 1 insert query like in function so cant loop over partnerid from arguments,are there any other way to do it?If there are no way to do it,I can change data types,example [[partnerid, magnitude],[partnerid, magnitude]......] or any other type witch will help solve this.

doable in one query, EG:

db=# with c(o, p, m) as (values (1, '{30,10,20}'::int[],'{46,59,12}'::int[]))
, op(i, status) as (values(20,1))
, mypart as (select o, unnest(p) pa, unnest(m) me from c)
select mypart.*
from mypart
left outer join op on i = pa
where i is null;
 o | pa | me
---+----+----
 1 | 30 | 46
 1 | 10 | 59
(2 rows)

so for you smth like:

INSERT INTO test.order_partner_magnitude(orderid, partnerid, magnitude)
with c(o, p, m) as (values (_orderId, __partnerids, __maginitude))
    , mypart as (select o, unnest(p) pa, unnest(m) me from c)
    select mypart.*
    from mypart
    left outer join test.order_partner on partner_id = pa
    where i is null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM