0

I just had starting taking classes for SQLite and one of my assignment wants me to create a trigger for an SQLite database. I know that certain functions from MySQL doesn't work on SQLite like the IF statement. Can anyone help me convert this MySQL trigger code to work on SQLite?

This is the trigger code in MySQL: (This code has been tested and works with the same database in MySQL)

CREATE TRIGGER `grade_update_check` 
BEFORE UPDATE ON `highschooler`
 FOR EACH ROW BEGIN
IF (NEW.GRADE > 12) 
THEN SET NEW.GRADE = OLD.GRADE;
 END IF;
 IF (NEW.GRADE < 9) 
THEN SET NEW.GRADE = OLD.GRADE;
 END IF; 
IF (SELECT COUNT(ID) FROM highschooler WHERE name = NEW.name and grade = NEW.grade) = 1 
THEN SET NEW.GRADE = OLD.GRADE; 
END IF; 
END

This my converted SQLite code for the same trigger:

CREATE TRIGGER 'grade_update_check' BEFORE UPDATE ON 'Highschooler' 
BEGIN
SELECT CASE
WHEN (SELECT grade FROM Highschooler WHERE NEW.GRADE > 12) THEN SET NEW.GRADE = OLD.GRADE;
WHEN (SELECT grade FROM Highschooler WHERE NEW.GRADE < 9) THEN SET NEW.GRADE = OLD.GRADE;
WHEN ((SELECT COUNT(ID) FROM highschooler WHERE name = NEW.name and grade = NEW.grade) = 1) THEN SET NEW.GRADE = OLD.GRADE;
END;
END;

It throws an error of Error: near "SET": syntax error when I try to execute it.

Any help or advice is highly appreciate it!

0

1 Answer 1

1

What you want from the trigger is to abort the update operation if any of the 3 conditions is met.

This can be done in SQLite like this:

CREATE TRIGGER grade_update_check BEFORE UPDATE ON Highschooler 
BEGIN
  SELECT 
    CASE
      WHEN NEW.GRADE < 9 OR NEW.GRADE > 12
        OR ((SELECT COUNT(ID) FROM highschooler WHERE name = NEW.name and grade = NEW.grade) = 1) 
      THEN RAISE(ABORT, 'your message here')
    END;
END;

The function RAISE(ABORT, ...) will abort the operation and the row will not be updated.
You can customize the message that you will get, or leave it empty.

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

2 Comments

How do you implement the SET NEW.GRADE = OLD.GRADE ?
@kimmieRak2 I don't. What SET NEW.GRADE = OLD.GRADE does is keep the current value and not update the column. This is done by RAISE(ABORT, ..) which aborts the update.

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.