触发器插入到多个表中
Trigger insert into multiple tables
我有 2 个 table 命名为:train_information 和 axle.
Train_information
有以下内容:
train_id (PK)
train_name
train_length
number_of_axles
axle
有以下内容:
axle_id (PK)
train_id(FK)
axle
当我在 train_information 上插入一些内容时,例如将数字 16 放入 number_of_axles。我希望 table axle 自动获取相同的信息。
如何使用触发器执行此操作?
编辑:
现在可以使用此代码:
CREATE TRIGGER TriggerName AFTER INSERT ON train_information
FOR EACH
ROW
BEGIN
INSERT INTO axle( train_id, axle )
VALUES (
NEW.train_id, NEW.number_of_axles
);
END
但是现在,它在 table axle 中输入例如数字 16
但我希望它像这样:
axle_id = 1
train_id = 1
axle = 1
axle_id = 2
train_id = 1
axle = 2
axle_id = 3
train_id = 1
axle = 3
这可能吗?
您可以在 Train_information
table 上创建 AFTER TRIGGER
,如下所示:
SQL
更多关于After Triggers in SQL
CREATE TRIGGER TriggerName
ON Train_information
FOR INSERT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO axle
(train_id, axle)
SELECT
train_id, 'axle_name'
FROM inserted
END
MySQL
更多关于After Triggers in MySQL
DELIMITER $$
CREATE TRIGGER TriggerName
AFTER INSERT ON Train_information FOR EACH ROW
BEGIN
INSERT INTO axle (train_id, axle)
VALUES (NEW.train_id, NEW.axle_name)
END;
$$
DELIMITER ;
我有 2 个 table 命名为:train_information 和 axle.
Train_information
有以下内容:
train_id (PK)
train_name
train_length
number_of_axles
axle
有以下内容:
axle_id (PK)
train_id(FK)
axle
当我在 train_information 上插入一些内容时,例如将数字 16 放入 number_of_axles。我希望 table axle 自动获取相同的信息。
如何使用触发器执行此操作?
编辑:
现在可以使用此代码:
CREATE TRIGGER TriggerName AFTER INSERT ON train_information
FOR EACH
ROW
BEGIN
INSERT INTO axle( train_id, axle )
VALUES (
NEW.train_id, NEW.number_of_axles
);
END
但是现在,它在 table axle 中输入例如数字 16 但我希望它像这样:
axle_id = 1
train_id = 1
axle = 1
axle_id = 2
train_id = 1
axle = 2
axle_id = 3
train_id = 1
axle = 3
这可能吗?
您可以在 Train_information
table 上创建 AFTER TRIGGER
,如下所示:
SQL 更多关于After Triggers in SQL
CREATE TRIGGER TriggerName
ON Train_information
FOR INSERT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO axle
(train_id, axle)
SELECT
train_id, 'axle_name'
FROM inserted
END
MySQL 更多关于After Triggers in MySQL
DELIMITER $$
CREATE TRIGGER TriggerName
AFTER INSERT ON Train_information FOR EACH ROW
BEGIN
INSERT INTO axle (train_id, axle)
VALUES (NEW.train_id, NEW.axle_name)
END;
$$
DELIMITER ;