1

I wrote a trigger which get trigered after update statement of table1. If there is no row in table1 based on the conditions, then update table2.

CREATE TRIGGER trigger1 
    AFTER UPDATE ON my_database.table1
FOR EACH ROW
BEGIN
DECLARE cnt int;
IF new.column1 = 1 THEN
   SELECT COUNT(1) INTO @cnt FROM my_database.table1 
   WHERE userID = 1 AND isDeleted = 0;
IF cnt = 0 THEN
   UPDATE my_database.table2 
   SET isDeleted = 1 
   WHERE userSeqID = new.userID;
END IF

It gives me error i nline number 4, I couldn't understand the problem

2 Answers 2

1

Every IF statement has to ended with END IF clause. Try this statement -

DELIMITER $$

CREATE TRIGGER trigger1
  AFTER UPDATE
  ON my_database.table1
  FOR EACH ROW
BEGIN
  DECLARE cnt int;
  IF NEW.column1 = 1 THEN
    SELECT COUNT(1) INTO cnt FROM my_database.table1 WHERE userID = 1 AND isDeleted = 0;

    IF cnt = 0 THEN
      UPDATE my_database.table2 SET isDeleted = 1 WHERE userSeqID = NEW.userID;
    END IF;
  END IF;
END$$

DELIMITER ;
Sign up to request clarification or add additional context in comments.

5 Comments

I want the second if statement inside the first if after the select statement.
I have changed my answer.
Still it gives me same error at declare statement. Kindly help me out.
Note that you set @cnt variable in first SELECT, but use cnt variable.
I have no problems with this query. Pay attention at using DELIMITERS also. But firstly fix problems inside the trigger.
1

The error on line 4 is because you're not using a delimiter.

Try this:

DELIMITER //
create trigger trigger1 after update on my_database.table1
for each row
begin
declare cnt int;
...
end if;
END;//

DELIMITER ;

You'll also need an END IF on the line after the select statement, and a terminal END; to match your begin, as I have in my example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.