PostgreSQL
 SQL >> Base de Dados >  >> RDS >> PostgreSQL

Implementando um UPDATE a partir de SELECT no Postgres

Repare no valor default da coluna qry_count:

CREATE TABLE t (
  a INTEGER PRIMARY KEY,
  b TEXT,
  entered_by INTEGER,
  qry_count INTEGER default 0
);

create function select_and_update(parameter text) returns setof t as $$
update t set qry_count = qry_count + 1
from ( select a from t where b = $1 ) s
where t.a = s.a;

select * from t where b = $1;
$$ language sql;

Agora consulte a tabela usando a função acima:

select * from select_and_update('a');

Atualizando conforme o comentário: você pode montar isso dinamicamente e, em vez de uma função, apenas envolver o código SQL — seja ele qual for — em uma transação. Não é preciso cursor.

begin;

update t set qry_count = qry_count + 1
from ( select a from t where b = 'a' ) s
where t.a = s.a;

select * from t where b = 'a';

commit;

Note que, em uma função SQL, todos os comandos veem o mesmo snapshot: o select final retornará os valores anteriores ao update. Se você precisa ver os valores já atualizados, use uma função plpgsql ou a forma explícita com transação acima.