PostgreSQL
 SQL >> Datenbank >  >> RDS >> PostgreSQL

Ein UPDATE auf Basis eines SELECT in PostgreSQL umsetzen

Beachte den Standardwert der Spalte 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; 

Frage die Tabelle nun über die obige Funktion ab:

select * from select_and_update('a'); 

Update gemäß dem Kommentar:

Du kannst es dynamisch aufbauen und musst – statt eine Funktion zu verwenden – den SQL-Code, worum auch immer es sich handelt, einfach in eine Transaktion verpacken. Cursor sind nicht nötig.

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;