Question

I would like to create a trigger so I could control negative values.

At first I tried...

CREATE TRIGGER POS_PROD
BEFORE INSERT
ON PRODUCTS
FOR EACH ROW
BEGIN
IF stock <0 OR price <0
THEN
RESIGNAL SET MESSAGE_TEXT = 'Please insert a positive value';
END IF;
END

The problem is, once I try to insert values, I got an error telling me "Price is an unknown field". Then I decided to try this...

CREATE TRIGGER POS_PROD
AFTER INSERT
ON PRODUCTS
FOR EACH ROW
BEGIN
IF stock <0 OR price <0
THEN
RESIGNAL SET MESSAGE_TEXT = 'Please insert a positive value';
ROLLBACK;
END IF;
END

But I got this error... Explicit or implicit commit is not allowed in stored function or trigger."

Thank you so much.

Was it helpful?

Solution

Try this

CREATE TRIGGER POS_PROD
BEFORE INSERT
ON PRODUCTS
FOR EACH ROW
BEGIN
IF NEW.stock <0 OR NEW.price <0
THEN
SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'Please insert a positive value';
END IF;
END;


INSERT INTO PRODUCTS values (10,20);
INSERT INTO PRODUCTS values (10,-20);

you have to use NEW to reference the values come from INSERT statement.

SQL FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top