简体   繁体   中英

How to create trigger to insert a sequence of numbers in postgresql; but the insert statement validated before ..?

Good morning everyone, I have a question about the following case:

I have a trigger and a function that inserts a land code, but when it works very well when inserting a row. But when an insert statement fails to execute for any problems in the expression, the sequence function generates a value before inserting the row, losing the order in the numeration.

There is a way to make a change in the trigger or function, to validate me before the INSERT expression before moving to the sequence function and thereby avoid those jumps of numeration.

Deputy code (triger and function) and images of the tables.

CODE:

CREATE TRIGGER trigger_codigo_pech
BEFORE INSERT ON independizacion
FOR EACH ROW
EXECUTE PROCEDURE codigo_pech();

CREATE OR REPLACE FUNCTION codigo_pech()
RETURNS trigger
AS $$

DECLARE
incremento INTEGER;
cod_inde text;

BEGIN
IF (NEW.cod_inde IS NULL OR NEW.cod_inde = '''' ) THEN
incremento = nextval ('codigo_pech');
NEW.cod_inde = 'PECH' || '-' || incremento;
END IF;
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';

CAPTURE QUERY RESULT

As you can see, it would also be necessary to make a trigger on the primary key to prevent jumps in the numeration.

I hope your help. Thank you

You can make incremento.cod_inde DEFERRABLE and INITIALLY DEFERRED:

ALTER TABLE incremento ALTER COLUMN cod_inde SET DEFAULT 0;
ALTER TABLE incremento
  ALTER CONSTRAINT incremento_cod_inde_key 
    DEFERRABLE INITIALLY DEFERRED;

Then assign the nextval('codigo_pech') in a AFTER INSERT trigger:

CREATE OR REPLACE FUNCTION codigo_pech_after() RETURNS trigger AS $$
BEGIN
  UPDATE incremento SET
    cod_inde = 'PECH-' || (nextval('codigo_pech'))::text
  WHERE id = NEW.id; -- replace id with your table's primary key
END;
$$ LANGUAGE plpgsql;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM