0

I created a trigger before inserting into the employee table to calculate its age, but trying to insert into the employee table returns the following erro Error Code: 1442. Can't update table 'employee' in stored function/trigger because it is already used by statement which invoked this stored function/trigger

CREATE TABLE IF NOT EXISTS person (
  ssn INT(20) NOT NULL,  
  name_person VARCHAR(200) NOT NULL,
  birth_date DATE NOT NULL,   
  PRIMARY KEY (ssn))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS employee (
  ssn_employee INT(20) NOT NULL,
  job_title VARCHAR(100) NOT NULL,
  age INT(10) DEFAULT NULL,
  PRIMARY KEY(ssn_employee),  
  FOREIGN KEY (ssn_employee)
  REFERENCES person (ssn)
  ON UPDATE CASCADE)
ENGINE = InnoDB;    

DELIMITER $$
CREATE TRIGGER employeeAge
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN   
    DECLARE dob DATE;
    DECLARE ssn_employee1 int;
    SELECT new.ssn_employee INTO ssn_employee1;
    SELECT person.birth_date into dob FROM person WHERE ssn = ssn_employee1;
    UPDATE employee
    SET new.age = DATEDIFF(dob, GETDATE());     
END
DELIMITER;$$
3
  • Seems to be pretty clear. You cannot do Update in the middle of Insert into the same table. Commented Jul 22, 2021 at 16:53
  • You can use generated column for age. Commented Jul 22, 2021 at 16:55
  • See techonthenet.com/mysql/triggers/before_insert.php Commented Jul 22, 2021 at 16:57

1 Answer 1

0

Thank you guys. I'm a beginner and the tips clarified. I did this:

```lang_sql
DELIMITER $$
CREATE TRIGGER employeeAge
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN   
    DECLARE dob DATE;
    DECLARE ssn_employee1 int;
    SELECT new.ssn_employee INTO ssn_employee1;
    SELECT person.birth_date into dob FROM person WHERE ssn = ssn_employee1;   
    SET new.age = TIMESTAMPDIFF(YEAR, dob, NOW());    
END;
DELIMITER $$
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.