E
E
esskimos2021-12-13 10:15:39
SQL
esskimos, 2021-12-13 10:15:39

How to correctly write a trigger for the sum of the row numbers when a new record appears?

We need a trigger that will enter all fields with a DECIMAL amount in the 'outcome' cell
Table:

CREATE TABLE maintable_pricetable (
    id           INTEGER       NOT NULL
                               PRIMARY KEY AUTOINCREMENT,
    transparency DECIMAL       NOT NULL,
    color        DECIMAL       NOT NULL,
    pis          DECIMAL       NOT NULL,
    purity       DECIMAL       NOT NULL,
    intensity    DECIMAL       NOT NULL,
    typicality   DECIMAL       NOT NULL,
    purity2      DECIMAL       NOT NULL,
    intensity2   DECIMAL       NOT NULL,
    persistence  DECIMAL       NOT NULL,
    typicality2  DECIMAL       NOT NULL,
    description  VARCHAR (200) NOT NULL,
    taster       VARCHAR (20)  NOT NULL,
    date         VARCHAR (10)  NOT NULL,
    harmony      DECIMAL       NOT NULL,
    outcome      VARCHAR (20),
    сipher       VARCHAR (6)   NOT NULL
);


An example of how it will look live. Trigger should write this in 'Outcome' aka 'outcome':

61b6f2f3bb7dd392312322.png

Simple generation won't work

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Tomulevich, 2021-12-13
@esskimos

There is an error in the author's comment.
To redefine the field value, you do not need to perform a separate update, it is enough to limit it BEFORE inserting:

CREATE TRIGGER maintable_pricetable_sum_trigger_insert
         BEFORE INSERT
            ON maintable_pricetable
      FOR EACH ROW
BEGIN
    SET NEW.outcome = (NEW.transparency + NEW.color + NEW.pis + NEW.purity + NEW.intensity + NEW.typicality + NEW.purity2 + NEW.intensity2 + NEW.persistence + NEW.typicality2 + NEW.harmony);
END;

At the same time, it is not entirely obvious why the amount is not considered during the UPDATE? This requires creating the same trigger on UPDATE:
CREATE TRIGGER maintable_pricetable_sum_trigger_update
         BEFORE UPDATE
            ON maintable_pricetable
      FOR EACH ROW
BEGIN
    SET NEW.outcome = (NEW.transparency + NEW.color + NEW.pis + NEW.purity + NEW.intensity + NEW.typicality + NEW.purity2 + NEW.intensity2 + NEW.persistence + NEW.typicality2 + NEW.harmony);
END;

And by the way, when the author got to the moment of updating the amount during UPDATE, he would start a fun fight with recursion.

E
esskimos, 2021-12-13
@esskimos

CREATE TRIGGER maintable_pricetable_sum_tr
         AFTER INSERT
            ON maintable_pricetable
      FOR EACH ROW
BEGIN
    UPDATE maintable_pricetable
       SET outcome = (NEW.transparency + NEW.color + NEW.pis + NEW.purity + NEW.intensity + NEW.typicality + NEW.purity2 + NEW.intensity2 + NEW.persistence + NEW.typicality2 + NEW.harmony) 
     WHERE id = NEW.id;
END;

Easier than I thought...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question