Problems creating a Delete Trigger to prevent some rows to be deleted - mysql

im trying to make my first delete trigger but im having a lot of errors. My goal is to create a trigger that prevents some rows to be deleted from a table, where the "created_id" equals 0.
I'm creating it on PHPMyAdmin. First i wasn't able to even create the trigger because i got a lot of errors. I was finally able to create this trigger:
CREATE TRIGGER `prevenirBorrado`
BEFORE DELETE ON `entidades_tipos`
FOR EACH ROW
BEGIN
IF entidades_tipos.created_by = 0 THEN
SIGNAL SQLSTATE 'U0042'
SET MESSAGE_TEXT = 'STRSQL No puedes borrar este registro!' ;
END IF ;
END
But now it won't let me delete any record from my table, getting this error:
SQLSTATE[42S02]: Base table or view not found: 1109 Unknown table 'entidades_tipos' in where clause
I was thinking about making AFTER DELETE and use 'ROLLBACK' but im not able to create the trigger without errors.
Thanks.

The SQLSTATE will raise an error. You could try adding an empty CONTINUE HANDLER immediately after the BEGIN statement.
Something like:
BEGIN
DECLARE CONTINUE HANDLER FOR SQLSTATE 'U0042' BEGIN END;
Also you need a semicolon at the end of your trigger declaration.

Related

Adding comments/notes

I have a trigger as follows:
DELIMITER //
create trigger highStockInsert
After insert on inventory
for each row Begin
if new.currentStock > 250 then Insert INTO higherStockList VALUES (new.prodName, new.StockCount, new.storeName, 'High Alert');
end if; end
// ;
Now when this trigger is act upon I would like mysql to give a message of some sorts, I was messing around with SQLSTATE but if this is triggered the table doesn't update it just blocks the whole insert statement from going through. I was wondering if its possible for the new row to be added but still give off a notification. I was looking if its possible to trigger a warning but found no luck either.
Thanks!

MySQL trigger creation - missing semicolon

im new in SQL programming. I need to create a trigger which after delete on "czytelnik" will also delete all records from "wypożyczył" which have the same CzytelnikID.
My code:
create trigger zadanie10
after update on czytelnik
for each row begin
if(old.Nazwisko != new.Nazwisko) then
delete from wypożyczył
where CzytelnikID=old.CzytelnikID;
end if;
end;
I got no idea what is worng in this code. Getting error after
"old.CzytelnikID;"
"end if;"
"end;"
I bypassed my problem this way:
create trigger zadanie10
after update on czytelnik
for each row
delete from wypożyczył
where old.CzytelnikID=wypożyczył.CzytelnikID and old.Nazwisko!=new.Nazwisko;
But if anybody know why i couldnt do the first way, please tell me.

Error to create a a trigger

I'm trying to create a trigger that everytime that insert a new data in my table tb_produto_parent, I need to update the columm cod_prod add one more.
Follow the trigger :
DELIMITER $$
create trigger trgAdicionaUm after insert
on tb_produto_parent
for each row
BEGIN
select cod_prod from tb_produto_parent;
update
tb_produto_parent set cod_prod = cod_prod +1;
END;
When I try to execute the code, MySQL show me a error :
Error Code: 1415 Not allowed to return a result set from a trigger.
Thanks !
There are two major problems with your code
you can't use SELECT on it own in a trigger because a trigger doesn't return a resultset to the client
you can't use DML statements (UPDATE in your case) on the same table (tb_produto_parent) on which you have your trigger in MySQL. Therefore even if you fix the first problem you still won't be able to update any row in tb_produto_parent within the trigger.
The only thing you can do in MySQL trigger is to alter values of columns of a row being inserted by using a BEFORE event for a trigger.
A possible solution is to use a stored procedure instead.
Error Code: 1415 Not allowed to return a result set from a trigger.
Looking at your trigger:
BEGIN
select cod_prod from tb_produto_parent;
update
tb_produto_parent set cod_prod = cod_prod +1;
END;
It would seem the select statement is the cause of this error. Remove it.

Protect column, disallow update, only allow insert if NULL in MySQL

I want to protect existing dates in a date column from being overwritten. So disallow updates to the date column and only allow inserts if the existing field value is NULL (date column default is NULL). Are triggers the only way to accomplish this in MySQL? If so, would the trigger below work?
create trigger date_check
before insert, update on date
for each row
begin
if(date IS NOT NULL) then
SIGNAL 'date already set'
end if ;
end ;
Background: I have a table with critical dates that was accidentally changed due to user error. I put some checks in the user interface to prevent this from happening again but want another layer of safety directly with the database if possible.
Yes, in MySQL triggers are the only way to do this. MySQL does not support constraints.
Your trigger is not exactly right. First, you have update on date, but this should be update on <table name>. Second, you are checking the date value used for the update. Perhaps you mean:
create trigger date_check_update
before update on <the table name goes here>
for each row
begin
if (old.date IS NOT NULL) then
SIGNAL 'date already set'
end if ;
end;
An insert trigger on this condition doesn't make sense.
If anyone like me stumble upon this thread and is getting syntax error, it's because "When you try to raise errors via SIGNAL you need to specify the SQLSTATE which is the error code and for the user defined generic error codes its 45000 along with the message text MESSAGE_TEXT"
So the SIGNAL line should look like this.
signal SQLSTATE VALUE '45000' SET MESSAGE_TEXT = 'Your custom error message';
See this answer for more details.
https://stackoverflow.com/a/42827275/4164651
Just combining the above two answers, however, if you are writing triggers directly at the terminal, you'll have to change the delimiter before writing the trigger and then change it back once done.
delimiter $$
create trigger date_check_update
before update on <the table name goes here>
for each row
begin
if (old.date IS NOT NULL) then
signal SQLSTATE VALUE '45000' SET MESSAGE_TEXT = 'Your custom error message';
end if ;
end $$
delimiter ;

mysql: Insert only if certain conditions are respected

I'm trying to find a way to check ,before adding a new tuple in a table, if the tuple respect some condition and in case of one of the conditions is not respected do not allow the insert.
I've thought of something like
DELIMITER //
CREATE TRIGGER t BEFORE INSERT ON Table
FOR EACH ROW
CALL CHECK1(…);
CALL CHECK2(…);
CALL CHECK3(…);
//
DELIMITER;
Where check1,check2,check3 are procedures that raise an exception if the NEW.(attributes) that I pass do not respect condition in the inserting table and/or with other tables.
Is this a correct and/or good way to make what I'm trying to do?
What is the best way to do that?
The best way to do it, is to do the data validation using stored procedures, instead of triggers. The trigger strategy is useful if you only want to filter incoming data. If the objective is to cancel an operation entirely when data values are unsuitable, you cannot do this in MySQL using a trigger.
I'm answering to reply(with a comment my answer would be incomprehensible) and to give more details:
I've used 2 strategies to make my goal, here 2 examples
1)if the check is easy
DELIMITER $$
create trigger RV5_1 before insert on Customer
for each row begin
IF(DATEDIFF(CURDATE(),NEW.birthdate)/365<18)
THEN
SIGNAL sqlstate '45006' set message_text = "too young to be a customer";
END IF;
END;
$$
DELIMITER ;
2) if the check is not easy and need cursors, variables etc
DELIMITER $$
create trigger T2 before insert on Table
for each row begin
IF (check1(NEW.[_some_attribute/s_]) or
check2(NEW.[_some_attribute/s_]))
THEN
SIGNAL sqlstate '45002' set message_text = "invalid insert";
END IF;
END;
$$;
DELIMITER ;
where check1 and check2 are stored functions that returns 0 if it's ok or 1 if there are problem with the new tuple.
Maybe someone with the same problem will found this helpful.