Peter Peter - 4 months ago 15
SQL Question

INSERT only when IF-condition is true

I would like to know if there is a possibility to Insert a row into a table when IF-Condition is true:

SET @Value1 := '1';
SET @Value2 := '2';
IF(@Value2 >= @Value1)
THEN INSERT INTO `Table`
(`Row1`, `Row2`)
VALUES
('Valuecheck', 'Second value is greater than first value');
END IF;


MySQL reports an error #1064 - You have an error in your SQL syntax, but I can't find that something is wrong. Insert should only be executed when IF-clause is true.

Answer

Based on this answer, the following should work:

SET @Value1 := '1'; 
SET @Value2 := '2'; 
INSERT INTO `table` (`Row1`, `Row2`) 
    VALUES 
    ('Valuecheck', 'Second value is greater than first value');
WHERE @Value2 >= @Value1