postgresql 如何创建具有两个不同选择的过程?

dnph8jn4  于 2022-11-23  发布在  PostgreSQL
关注(0)|答案(2)|浏览(206)

我想创建一个接收两个id的过程,在一个表中进行两次选择并返回数据,然后我想使用先前返回给我的结果在另一个表中执行更新,如何做到这一点?
这是一个例子,说明了目前的情况

create or replace procedure transfer(
 origin int,
 destination int, 
amount dec
)
language plpgsql    
as $$

begin

select id as id_user_origin
from users
where id = origin 

select id as id_user_destination
from users
where id = destination

-- subtracting the amount from the sender's account 
update wallets 
set balance = balance - amount 
where id = id_user_origin;

-- adding the amount to the receiver's account
update wallets
set balance = balance + amount 
where id = id_user_destination;

commit;
end;$$
8i9zcol2

8i9zcol21#

您需要将不同选择的结果存储到变量中:

declare
    id_user_origin int;
begin
    select id into id_user_origin from users where id = origin ;
     
  .....
  update... ;
4bbkushb

4bbkushb2#

您可以将该过程缩减为单个DML语句。

create or replace procedure transfer(
      origin int
    , destination int  
    , amount dec
)
language plpgsql   
as $$
begin
    update wallets 
       set balance = case when id = origin 
                          then balance - amount
                          else balance + amount
                     end 
      where id in (origin, destination) 
        and exists (select null from wallets where id = destination)
        and exists (select null from wallets where id = origin and balance >= amount);
 
    commit; 
end ;
$$;

exists在技术上不是必需的,但可以防止过程接收无效参数。请参阅demo,其中包含一条消息,指出由于无效用户或余额不足而未执行更新。如果包含此消息,则通常会写入日志表。

相关问题