Business requirement: When a patient record is inserted, we want to have an ID generated of the format 001-2022, 002-2022 (serial no. plus year). When the year changes, the serial number should start with 1 again. I wrote the following MySQL trigger before Patient record insert:
delimiter //
drop trigger generate_yearly_id;
CREATE TRIGGER generate_yearly_id BEFORE insert ON patients
FOR EACH ROW
BEGIN
DECLARE last_id integer;
DECLARE current_year date;
DECLARE yearly_id integer;
IF new.CustomYearlyId is null then
begin
set @last_id := (select max(yearlyid) from patients where
year(createdon)=year(curdate()));
if (last_id is null) then
set @yearly_id := last_id + 1;
else
set @yearly_id := 1;
end if;
set new.yearlyid = yearly_id;
end;
end if;
END;//
I want to increment the yearlyid column upon insertion of a Patient record. However, I am only getting 0 as YearlyId for every insertion. Why is that? YearlyId column if of type int.