Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

sql - Execute MySQL Trigger only when specific NEW value exists

I want to execute my MySQL(MariaDB) Trigger only when a specific value in NEW exists and is not null.

How can I wrap my Trigger in an if clause that checks if the new insert contains a value for lets say Name. So if theres a new insert or update query which don't set the field Name I don't want to run the trigger.

I've tried

IF NEW.Name IS NOT NULL
BEGIN
 ...
END

But it doesn't work.

My actual trigger code does properly use the values from NEW.

My trigger looks like this.

INSERT INTO Produkte (Textilkennzeichen, Produktnummer, Bestand, createdAt, updatedAt)
VALUES (NEW.Textilkennzeichen, NEW.Produktnummer,
@Bestand := (
    SELECT IFNULL(SUM(`Anzahl`), 0)
    FROM Eintragungen
    WHERE Produziert = true
    AND Textilkennzeichen = NEW.Textilkennzeichen
    AND Produktnummer = NEW.Produktnummer
)
-
((
    SELECT IFNULL(SUM(`Anzahl`), 0) 
    FROM Eintragungen
    WHERE Verkauf = true
    AND Textilkennzeichen = NEW.Textilkennzeichen
    AND Produktnummer = NEW.Produktnummer
)
+
(
    SELECT IFNULL(SUM(`Anzahl`), 0)
    FROM Eintragungen
    WHERE Schenkung = true
    AND Textilkennzeichen = NEW.Textilkennzeichen
    AND Produktnummer = NEW.Produktnummer
)
+
(
    SELECT @amount_r := IFNULL(SUM(`Anzahl`), 0)
    FROM Eintragungen
    WHERE Reklamation = true
    AND Textilkennzeichen = NEW.Textilkennzeichen
    AND Produktnummer = NEW.Produktnummer
)), NOW(), NOW())
ON DUPLICATE KEY UPDATE Bestand = @Bestand
question from:https://stackoverflow.com/questions/65905144/execute-mysql-trigger-only-when-specific-new-value-exists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Code should be

if something then
   insert ...;
endif;

presumably your ide makes the create..for each row begin...end

so you end up with create trigger.. for each row begin if something then insert ...; endif; end


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...