The following is the definition of the patient table:
Patients table Columns: PatientId int AI PK FirstName longtext LastName longtext Email longtext NIC longtext Phone longtext Address longtext City longtext Country longtext DOB datetime(6) Gender longtext Reference longtext SerialNumberYear smallint SerialNumber int DoctorId int CreatedOn datetime(6) UpdatedOn datetime(6) CreatedBy longtext SMS_Allowed tinyint(1) Email_Allowed tinyint(1) SpecialConcern1 longtext SpecialConcern2 longtext SpecialConcern3 longtext SpecialConcern4 longtext CustomYearlyId longtext YearlyId int
I have the following trigger on this table in MySQL:
CREATE TRIGGER generate_yearly_id BEFORE INSERT ON clinic.patients FOR EACH ROW BEGIN DECLARE last_id INTEGER default 10; DECLARE current_year DATE; DECLARE yearly_id INTEGER default 0; IF NEW.CustomYearlyId IS NULL THEN BEGIN INSERT INTO DEBUG VALUES (null,"start trigger"); #SET @last_id := (SELECT max(yearlyid) FROM patients WHERE # YEAR(createdon)=YEAR(CURDATE())); IF last_id IS NOT NULL THEN BEGIN SET @yearly_id = 1; INSERT INTO DEBUG VALUES (null, concat("in if lastid is not null ",@yearly_id)); END; ELSE BEGIN #SET @yearly_id := 1; END; END IF; SET NEW.yearlyid := @yearly_id; END; END IF; END;// delimiter ;
Statement SET @yearly_id = 1;
works fine. But if I change it to SET @yearly_id = @last_id;
the trigger fails. What did I do wrong while doing this assignment? last_id has default value so do I need to initialize it?
The code below works perfectly. The difference is 1. The variable has been initialized before use. Apparently the default value is not enough. 1. Used count in "if" condition instead of testing "is null".