drop trigger if exists on_addupd_situacao_formulario on situacao_formulario;
drop function if exists on_addupd_situacao_formulario();

create function on_addupd_situacao_formulario() returns trigger
	as $$
begin
	if NEW.data_verificacao is null or NEW.data_atualizacao > NEW.data_verificacao then
		NEW.codigo = 1;
	elsif NEW.correcao is not null then
		NEW.codigo = 2;
	else
		NEW.codigo = 3;
	end if;
	return NEW;
end;
$$ 
	language plpgsql;

create trigger on_addupd_situacao_formulario
	before insert or update on saude.situacao_formulario
	for each row
	execute procedure on_addupd_situacao_formulario();

