You don’t need a trigger
. It is only necessary that you create a foreign key
column and determine that it is not possible to delete if there is a child:
ALTER TABLE ocorrencias
ADD CONSTRAINT frk_ocorrencias_usuario
FOREIGN KEY(responsavel)
REFERENCES usuario(id)
ON DELETE RESTRICT
FOREIGN KEY Constraints
The type of Constraint that maintains database Consistency through a Foreign key Relationship.
In free translation:
FOREIGN KEY RESTRICTIONS
The type of constraint that maintains database consistency by applying the relationship between foreign keys.
If you really need to perform the check with trigger
(what is not recommended) you can do it this way:
DELIMITER $
CREATE TRIGGER trg_bd_usuario BEFORE DELETE
ON usuario
FOR EACH ROW
BEGIN
IF (SELECT 1 = 1 FROM ocorrencias WHERE responsavel = OLD.id) THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Este usuário possui ocorrências e não pode ser deletado.';
END IF;
END$
Recalling that the SIGNAL
only works in the MySQL
from the version 5.5
.
Who gave the
downvote
could explain what’s wrong in the answer so I can correct?– Sorack
Sorack was not I who denied, but I can assume that it is because the person may have thought that the question is so unclear that it did not deserve an answer, maybe it is not against your answer and much less against you, it may be a way of saying, do not answer questions "unclear". I’m not asserting, just a theory. I also won a downvote on a question that received closing votes yesterday :/, but seem to me legitimate votes. See you later
– Guilherme Nascimento
@Guilhermenascimento one of the problems is the
downvote
without explanation. If the person said that I would argue that the question is clear to me. It is simple and will probably not help anyone in the future but what has been asked is very simple. Aside from that I only answered the question, if someone does not agree with the question has to vote to close, do not deny who answered, after all my answer is not incorrect and by the way goes beyond the question. Second page of "vote down":...Ou uma resposta que é clara e talvez perigosamente incorreta.
otherwise has other approaches.– Sorack
Anyway, I hope the person who did this reads carefully the part of Privileges - Vote Against since the incorrect negative vote is detrimental to the functioning of the site.
– Sorack
Good morning, I needed to do via Rigger because it is a prerequisite, it has as?
– Jefferson Kist
@Jeffersonkist added the example with
trigger
– Sorack
Thanks buddy, solved my problem =).
– Jefferson Kist