I want to use the CHECK constraint in MySQL, but it is not supported. (Unlike other RDBMS, it will understand but not enforce the CHECKs.)
I have seen some workarounds with triggers. But they tend to set a default value to the field in question instead of returning an error.
Is it possible to construct a trigger that returns an error if a condition is not met?
Ultimately I want a trigger that copies a CHECK constraint.
BEFORE triggers, unlike check constraints, are not restricted to access other values in the same row of the same table. During a SET INTEGRITY operation on a table after a LOAD operation, triggers (including BEFORE triggers) are not executed. Check constraints, however, are verified.
Check constraints are fired with each row. Triggers can be written so all inserted rows are checked as a single batch and that is often faster. Also, a trigger can be written so it is only fired if some column(s) of interest are set/modified.
The trigger event that initiates the trigger action can be an INSERT, DELETE, UPDATE, or a SELECT statement. The MERGE statement can also be the triggering event for an UPDATE, DELETE, or INSERT trigger.
A database trigger is not the same as an integrity constraint. A database trigger defined to enforce an integrity rule does not check data already loaded into a table. Therefore, it is recommended that you use a trigger only when the integrity rule cannot be enforced by an integrity constraint.
when you are updating data :
delimiter $$
create trigger chk_stats1 before update on stats
for each row
begin
if new.month>12 then
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Cannot add or update row: only';
end if;
end;
$$
when you are inserting data :
delimiter $$
create trigger chk_stats before insert on stats
for each row
begin
if new.month>12 then
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Cannot add or update row: only';
end if;
end;
$$
these trigger will work as check constraint ,work before insert or update and check month, if month >12 gives error .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With