How to get the result of SELECT statement inside a transaction?

£可爱£侵袭症+ 提交于 2021-02-07 14:25:17

问题


I can't get information of that simple question over the PostgreSQL documentation, over the Web or even here on StackOverflow... I must not unsertand something essential here.

I am making a simple SELECT/UPDATE transaction in PostgreSQL:

START TRANSACTION;
SELECT "column" FROM "table" WHERE "criterion" = 'value' AND "activated" = true;
UPDATE "table" SET "activated" = false WHERE "criterion" = 'value';
COMMIT

Basically, I need to get the value of a column when its activated state is true and then deactivate it. PostgreSQL tells me that there was a 1 row result that has been cancelled

The same happens if I do the following (basically the same transaction withotu the UPDATE statement):

START TRANSACTION;
SELECT "column" FROM "table" WHERE "criterion" = 'value' AND "activated" = true;
COMMIT

What don't I understand about transactions? Can't any SELECT output get out of a transaction block?


回答1:


This will return all "column"'s values from the updated rows:

UPDATE "table" SET "activated" = false WHERE "criterion" = 'value' AND "activated" = true
returning "column";

There is no relation to the transaction.

returning will return the values as if a select was issued:

insert into foo (ticket, row, archived) values (3,7,true) returning *;
 ticket | row | archived 
--------+-----+----------
      3 |   7 | t

update foo
set archived = true
where not archived
returning *;
 ticket | row | archived 
--------+-----+----------
      2 |   5 | t


来源:https://stackoverflow.com/questions/13058790/how-to-get-the-result-of-select-statement-inside-a-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!