简体   繁体   中英

mysql trigger syntax error in maria db

I was trying to make one trigger , so that i can check for any negative insertion of age . I tried below query but its showing below error .

CREATE TRIGGER agecheck 
    BEFORE INSERT ON people
FOR EACH ROW
BEGIN
    (CASE WHEN people.age  > 0 THEN  people.age ELSE 0 END )
END

ERROR CODE:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CASE WHEN people.age > 0 THEN 1 ELSE 0 END ) END' at line 5

Am i doing anything wrong in the syntax?

The statement you have in your trigger is not a statement. It's just an expression. This is not a thing you can use as a statement by itself.

I'm just guessing at what you are trying to do: make sure age is not negative. You could probably do this by declaring the column as TINYINT UNSIGNED , but if you want to do it with a trigger:

FOR EACH ROW
BEGIN
    SET NEW.age = CASE WHEN NEW.age > 0 THEN NEW.age ELSE 0 END;
END

In a trigger, always reference the columns of the respective triggered row with NEW.<columnname> or OLD.<columnname> .

Another expression that works just as well:

FOR EACH ROW
BEGIN
    SET NEW.age = GREATEST(NEW.age, 0);
END

There's no specific advantage for this alternative, I'm just showing another use of an expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM