1

I'm trying to control a transaction with a procedure but I'm getting an error I cannot resolve.

This is the code:

drop table if exists cuentas;

create table cuentas (
    id serial,
    nombre varchar(100) not null,
    saldo dec(15,2) not null,
    primary key(id),
    constraint saldo CHECK(saldo > 5000)
);


insert into cuentas(nombre, saldo)
values('Carlos',10000);

insert into cuentas(nombre, saldo)
values('Cesar',10000);

SELECT * FROM cuentas;

drop procedure if exists transferir;

create or replace procedure transferir(id_emisor int,id_receptor int,cantidad dec)
language plpgsql    
as $$
begin
-- adding the amount from the recievers's account 
update cuentas 
set saldo = saldo + cantidad 
where id = id_receptor;
-- substracting the amount to the sender's account
update cuentas 
set saldo = saldo - cantidad 
where id = id_emisor;
commit;

EXCEPTION
    WHEN check_violation THEN
        RAISE NOTICE 'Violación de saldo.';
        rollback;
        commit;
end;$$

When I try to execute:

call transferir(1,2,1000);

I get:

ERROR:  no se puede comprometer mientras hay una subtransacción activa
CONTEXT:  función PL/pgSQL transferir(integer,integer,numeric) en la línea 13 en COMMIT
Estado SQL: 2D000

Error:

Can anybody see what I'm doing wrong?

1
  • 1
    What is your Posgres version? (select version(); will tell you). Did you turn on autocommit before calling the procedure? Commented Feb 26, 2021 at 13:28

1 Answer 1

1

Hi 'a_horse_with_no_name' and forum administrators, Sorry for using this section which I know is not the correct place but I can't answer a_horse_with_no_name nor comment his suggestion.
I'm using Postgresql version 12.4. Also I unselect autocommit. But Postgresql throws the error. Thanks

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, you could try to only use one account. If you had used the account you started the question with, you could have simply edited it and add the information you've been asked for...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.