在插入表之前创建触发器
Posted
技术标签:
【中文标题】在插入表之前创建触发器【英文标题】:Create trigger before insert in table 【发布时间】:2021-09-29 23:02:44 【问题描述】:我在插入员工表之前创建了一个触发器以计算其年龄,但尝试插入员工表会返回以下错误 错误代码:1442。无法在存储函数中更新表“员工”/触发器,因为它已被调用此存储函数/触发器的语句使用
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;$$
【问题讨论】:
似乎很清楚。您不能在插入到同一个表的中间进行更新。 您可以使用生成的列作为年龄。 见techonthenet.com/mysql/triggers/before_insert.php 【参考方案1】:谢谢你们。我是初学者,提示已澄清。我这样做了:
```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 $$
【讨论】:
以上是关于在插入表之前创建触发器的主要内容,如果未能解决你的问题,请参考以下文章
创建将 UNIX_TIMESTAMP() 插入日志表的触发器
在oracle中插入表B后创建触发器以将新行添加到表A中时出错