简体   繁体   中英

How to use variables from an insert statement inside sql trigger

What I want is something simple. After searching the net for a while I can't find exactly what I want. Given the sql below:

CREATE TABLE accounts (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(50) DEFAULT NULL,
    PRIMARY KEY (id)
);


CREATE TABLE meal_plans (
    planid int(11) NOT NULL AUTO_INCREMENT,
    planname varchar(255) DEFAULT 'Default',
    account_id int(11) NOT NULL,
    created_date date DEFAULT GETDATE(),
    UNIQUE (planname, account_id),
    FOREIGN KEY (account_id) REFERENCES accounts (aid),
    PRIMARY KEY(planid)
); 


DELIMITER //
CREATE TRIGGER addDefaultPlans
ON accounts
AFTER INSERT
AS
    BEGIN
        INSERT INTO meal_plans (account_id) VALUES (@thenewaccount);
    END //
DELIMITER ;

What I am aiming for is a trigger that is supposed to create a default meal plan for each new account using the foreign key in the meal_plans table, however I am unaware as to how to handle the variables of the INSERT statement that triggered the trigger. What could be done is to get the id of the last row in the accounts table after insert and use it however I think this is risky. Any comments would be appreciated.

Within the trigger, you should be able to use NEW.account_id to reference the account_id on the new row that caused the trigger to be fired.

Reference https://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html

(Note that your trigger is defined as "ON recipes" not "ON accounts", which I think is a mistake, although it doesn't change this answer.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM