1.
I notice in your trigger, your code says:
INSERT INTO LYNX.TRANS_AUDIT
(TA_ID, TA_KEY_VALUE, TA_TABLE_CHANGED, TA_FIELD_CHANGED, ...)
VALUES
(TA_ID, N.UNIT_ID , 'PUNIT', 'FLEET_ID', ...);
But shouldn't the VALUES clause contain vTA_ID
instead?
INSERT INTO LYNX.TRANS_AUDIT
(TA_ID, TA_KEY_VALUE, TA_TABLE_CHANGED, TA_FIELD_CHANGED, ...)
VALUES
(vTA_ID, N.UNIT_ID , 'PUNIT', 'FLEET_ID', ...);
However, calculating vTA_ID with your query, may not be your most efficient option.
2.
You could create a SEQUENCE object, and let it always calculate new values.
CREATE SEQUENCE TRANS_AUDIT_SEQ AS INTEGER;
Then in your trigger,
INSERT INTO LYNX.TRANS_AUDIT
(TA_ID, TA_KEY_VALUE, TA_TABLE_CHANGED, TA_FIELD_CHANGED, ...)
VALUES
(NEXT VALUE FOR TRANS_AUDIT_SEQ, N.UNIT_ID , 'PUNIT', 'FLEET_ID', ...);
3.
But what may suit you best, may be to define your ID column AS IDENTITY
CREATE TABLE LYNX.TRANS_AUDIT (
TA_ID INTEGER GENERATED BY DEFAULT AS IDENTITY,
...
PRIMARY KEY (TA_ID)
);
Then in your trigger, you do not need to specify the value, since it will be generated for you:
INSERT INTO LYNX.TRANS_AUDIT
(TA_KEY_VALUE, TA_TABLE_CHANGED, TA_FIELD_CHANGED, ...)
VALUES
(N.UNIT_ID , 'PUNIT', 'FLEET_ID', ...);
This is most likely the best of the 3 solutions for you, unless there are other factors not mentioned.
You can do an UPDATE JOIN
of table1
against a subquery that aggregates id
counts in table2
UPDATE
table1 A INNER JOIN
(SELECT id,COUNT(1) idcount
FROM table2 GROUP BY id) B
USING (id)
SET A.number = B.idcount;
This query will not get every id
. Why? If there is an id
in table1
that is missing in table2
, that does not write a zero in the numbers
column.
To cover for id
values missing in table2
, run this one:
UPDATE
table1 A LEFT JOIN
(SELECT id,COUNT(1) idcount
FROM table2 GROUP BY id) B
USING (id)
SET A.number = IFNULL(B.idcount,0);
Give it a Try !!!
Best Answer
While this trigger function is expensively incorrect and needs to be fixed, it can't explain the problem you describe. There must be some other cause, not evident from your question, yet. Some other broken trigger on
table1
ortable2
?This trigger updated the same row in
table2
once for every row intable1
and the final value oftable2.code_tranche
was an arbitrary pick fromtable1
.Remove
from schema.table1
:And I assume you are aware that
user
is s synonym forcurrent_user
, returning the user name of current execution context. If it's supposed to be a column name, you have to useNEW."user"
instead. (But never use reserved words as identifiers to begin with - like jjanes commented.)Typically, this kind of trigger indicates a problem with your db design. Try to remove redundancy. Storing information in one table should suffice.