简体   繁体   中英

How to execute two transactions concurrently in Postgresql?

I want to execute concurrently two transactions in Postgresql and that's what I've got

--The first transaction should modify the age of Paul
BEGIN;
DECLARE newage INTEGER;
--the original age of Paul is 32
newage := Select age FROM COMPANY WHERE name = Paul;
newage := newage+10;
update company set age := Sage where name = Paul;
commit;


--The second Transaction shows all information about Paul including his age
Begin
select * from company where name = 'Paul';
commit;

Both parts were written in the same SQL Editor. My first problem is that it doesn't compile, I obtain the message

ERROR:  syntax error at or near "INTEGER"
LINE 2: DECLARE newage INTEGER;

How can I improve my code to execute it? Can anyone help me? Thanks!

  1. In PostgreSQL you cannot declare variables in SQL, but you can do it in pl/pgsql
  2. DECLARE keyword creates a cursor, not a variable.
  3. Use SELECT INTO to set value to the newage
  4. Use DO to execute pl/pgsql. It will be executed in a single transaction.

So the result query looks like:

DO $$ DECLARE
    newage INTEGER;
BEGIN
    SELECT age INTO newage FROM companey WHERE name = 'Paul';
    newage := newage+10;
    UPDATE company SET age = newage where name = 'Paul';
END $$:

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