[英]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. 有一种方法可以更改触发器或函数,在移至序列函数之前先在INSERT表达式之前对我进行验证,从而避免计算的跳跃。
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';
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: 您可以incremento.cod_inde
DEFERRABLE并初步递延:
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: 然后在AFTER INSERT触发器中分配nextval('codigo_pech')
:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.