database - How to return a new value in a trigger from a cte in PostgreSQL -
from previous question in postgresql (9.3), how check sequence efficiently used , unused values in postgresql, have table chart_gap has list of unused chart numbers table charts:
create table chart_gap (chart_number integer);
in trying understand triggers bit more, have added following trigger procedure taken more or less question:
create or replace function next_chart() returns trigger $body$ begin -- check empty chart number if new.chart_number null ins ( select chart_number chart_gap pg_try_advisory_xact_lock(chart_number) limit 1 ) delete chart_gap c using ins i.chart_number = c.chart_number; new.chart_number := select chart_number ins; <--wrong! end if; return new; end; $body$ language plpgsql volatile;
the trigger procedure tied charts file with:
create trigger next_chart before insert on charts each row execute procedure next_chart();
what attempting replace empty chart number field in charts whenever new chart record added. can done in trigger? (and correct syntax??)
in plpgsql
function can use query returning ... ...
follows:
create function next_chart() returns trigger $body$ begin -- check empty chart number if new.chart_number null ins ( select chart_number chart_gap pg_try_advisory_xact_lock(chart_number) limit 1 ) delete chart_gap c using ins i.chart_number = c.chart_number returning i.chart_number new.chart_number; end if; return new; end; $body$ language plpgsql volatile;
Comments
Post a Comment