2

I have got 2 tables named: train_information and axle.

Train_information

has the folowing:

train_id (PK)
train_name
train_length
number_of_axles

axle

has the folowing:

axle_id (PK)
train_id(FK)
axle

When I insert something on train_information and let's say for example put the number 16 in number_of_axles. I want the table axle to get that same information automatically.

How do i do this with a trigger?

EDIT:

it works now with this code:

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

But right now, it enters for example the number 16 in the table axle but i want it to go like:

axle_id = 1
train_id = 1
axle = 1

axle_id = 2
train_id = 1
axle = 2

axle_id = 3
train_id = 1
axle = 3

Is this posible?

1 Answer 1

1

You can create AFTER TRIGGER on Train_information table, something like this:

SQL More about 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 More about 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 ;
Sign up to request clarification or add additional context in comments.

6 Comments

I get the following error: MySQL meldt: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON train_information FOR INSERT AS BEGIN SET NOCOUNT ON ' at line 2 I'm using phpmyadmin
So are you using MySQL?
Yes, i click on: add trigger. There i have to fill in the name etc. and a field that says: Definition. There i fill the code in.
Updated my answer how It should be in MySQL, check It. Also added documentation to learn about triggers.
It still gives a syntax error, but i think i'm doing something wrong. I'l take a look at the documentation! thank you!
|

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.