1

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.

Peter
  • 1,224
  • 3
  • 16
  • 28

2 Answers2

2

You can do an INSERT...SELECT and put your condition(s) in a WHERE clause; however, since MySQL requires a FROM and you are not referencing a table, you'll need to use its "dummy" table, called DUAL.

Like so:

SET @Value1 := '1'; 
SET @Value2 := '2'; 

INSERT INTO `Table`(`Row1`, `Row2`) 
SELECT 'Valuecheck', 'Second value is greater than first value'
FROM DUAL
WHERE @Value2 >= @Value1
;
Uueerdo
  • 15,723
  • 1
  • 16
  • 21
1

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
Community
  • 1
  • 1
SebHallin
  • 881
  • 6
  • 11
  • You'll need to edit; that answer does not use `VALUES`, but the answer referenced is appropriate. – Uueerdo Jul 21 '16 at 17:46
  • 4
    How can this possibly be right and the accepted answer?? You cannot have a `WHERE` on an `INSERT`, the syntax is wrong anyway (extra `;` before `WHERE`), and the whole point of the linked (correct) answer is that it says you *must* be using `INSERT INTO ... SELECT ... WHERE`, not `VALUES`. Grrrr.... – JonBrave Nov 29 '18 at 14:40