Help with writing MySQL trigger
With the following tables:
Party.(PartyId, PartyTypeCode)
and Member.(MemberId (FK), Name)
I want to fill in the MemberId column with the value of the PartyId after a new Party is created.
I know the SQL below is wrong but that is why I am looking for help in making it right.
CREATE TRIGGER tgr_member_create AFTER INSERT on Party
FOR EACH ROW BEGIN
IF NEW.PartyTypeCode = 'M' THEN
INSERT Member(MemberId)
VALUES('Party.PartyI开发者_运维百科d')
END IF;
END;
Thanks to Nanne's input this is what works:
DELIMITER $$
CREATE TRIGGER tgr_member_create AFTER INSERT on Party
FOR EACH ROW BEGIN
IF NEW.PartyTypeCode = 'M' THEN
INSERT Member (MemberId,Name)
VALUES(NEW.PartyId, 'someName');
END IF;
END;$$
DELIMITER ;
Your values should call the NEW
row, just as you do with the partytypecode I guess? I'm assuming
delimiter $$
CREATE TRIGGER tgr_member_create AFTER INSERT on Party
FOR EACH ROW BEGIN
IF NEW.PartyTypeCode = 'M' THEN
INSERT Member (MemberId,Name)
VALUES(NEW.PartyId, 'someName')
END IF;
END;$$
Pay attention to the delimiter code. Because you are using ;
inside, you can't use it as a normal 'end-of-command' token. that's why the &&
For debugging: Make sure the query works when you perform it outside a trigger:
INSERT Member (MemberId,Name)
VALUES(party-id goes here, 'someName')
There could be a small mistake there. Fill in your partyId obviously.
Try this
CREATE TRIGGER tgr_member_create AFTER INSERT on Party
FOR EACH ROW BEGIN
IF NEW.PartyTypeCode = 'M' THEN
INSERT Member(MemberId)
VALUES('New.PartyId')
END IF;
END;
精彩评论