Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF in MySQL trigger [closed]

Tags:

mysql

triggers

Trying to create MySql trigger

CREATE TRIGGER updVisible AFTER UPDATE ON photos
FOR EACH ROW 
BEGIN
    IF NEW.Status = 2 THEN
        UPDATE otherTable SET IsVisible=0 WHERE PID=NEW.PID
    END IF;
END;

But I got error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END IF' at line 6

MySQL version: 5.1.41-community What am I doing wrong?

UPD1. This doesn't help

DELIMITER //
CREATE TRIGGER updVisible AFTER UPDATE ON photos
FOR EACH ROW 
BEGIN
    IF NEW.Status = 2 THEN
        UPDATE otherTable SET IsVisible=0 WHERE PID=NEW.PID
    END IF
END//
DELIMETER ;

Error:

Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END IF END' at line 6

I have root access and using MySql Workbench 5.2.31 CE

like image 414
Lari13 Avatar asked Feb 02 '26 23:02

Lari13


1 Answers

This works in my machine!

mysql> DELIMITER //
mysql> CREATE TRIGGER test1 AFTER UPDATE ON test
    -> FOR EACH ROW
    -> BEGIN
    ->     IF NEW.itemId = '2' THEN
    ->         UPDATE test1 SET col1=0 WHERE col2=NEW.`value`;
    ->     END IF;
    -> END//
Query OK, 0 rows affected (0.05 sec)

mysql> DELIMiTER ;
mysql> desc test;
+--------+--------------+------+-----+---------+-------+
| Field  | Type         | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| itemId | varchar(100) | YES  |     | NULL    |       |
| key    | varchar(100) | YES  |     | NULL    |       |
| value  | varchar(100) | YES  |     | NULL    |       |
+--------+--------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

mysql> desc test1;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| col1  | varchar(100) | YES  |     | NULL    |       |
| col2  | varchar(100) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql>
like image 155
Nishant Avatar answered Feb 05 '26 13:02

Nishant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!