0

hi i am using MySQL TRIGGERS , i am using MySQL 5.5.8 , i have a table . since MySQL not allow CHECK Constraint , i used a TRIGGER to check an input value is wrong , if the input value is wrong i tried to gave a message and stop insert the records to the table . but it ignores my TRIGGER , record insert to the table if it contains invalid data .

table

CREATE TABLE pupil_data
(
PupilID int(10) NOT NULL  AUTO_INCREMENT,
PupilForeName varchar(255) NOT NULL,
PupilLastName varchar(255) NOT NULL,
Gender CHAR(1),
DateOfBirth  DATE ,
PhoneNumber int(10) ,
FamilyID int(10) NOT NULL,
PRIMARY KEY (PupilID),
FOREIGN KEY (FamilyID) REFERENCES family_data(FamilyID)  
ON DELETE CASCADE
ON UPDATE CASCADE
,
UNIQUE (PhoneNumber)
) ENGINE=innodb;

trigger

DELIMITER $$
CREATE TRIGGER `check_pupil_before_insert` BEFORE INSERT ON `pupil_data`
FOR EACH ROW  BEGIN
  IF  CHAR_LENGTH( NEW.DateOfBirth ) < 4 THEN
       SIGNAL SQLSTATE '12345'
        SET MESSAGE_TEXT := 'check constraint on pupil_data.DateOfBirth  failed'
    END IF;
END$$  
DELIMITER ;

i want to check if the value entered for DateOfBirth is less than 4 characters , then don't insert the record , give an error message but .

enter image description here

the value of DateOfBirth is 0 , so i suppose it should give an error , but as you can see it is executing ignoring it.

what is the reason , i am doing this wrong , please help, thanks in advance.

UPDATE

enter image description here

Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193

1 Answers1

3

Your Trigger defination is wrong . You are using date data type and for that you are checking char length . which is probably wrong because mysql by default enters date as '0000-00-00' Plus your syntax is wrong ...

So your Trigger defination should be like

 CREATE TRIGGER `check_pupil_before_insert` BEFORE INSERT ON `pupil_data`
FOR EACH ROW  BEGIN
 IF   NEW.DateOfBirth = '0000-00-00' THEN
   SIGNAL SQLSTATE '12345'
    SET MESSAGE_TEXT = 'check constraint on pupil_data.DateOfBirth  failed';
 END IF;
END$$  

Try this ..

alwaysLearn
  • 6,882
  • 7
  • 39
  • 67