MySQL Forums
Forum List  »  Newbie

Sproc to Insert Into Multiple Tables
Posted by: Arthur Chan
Date: December 14, 2018 01:46AM

SCENARIO:
=========
Please consider this contrived relationship
Part ||---0< XOrderPart <0---|| Order

CREATE TABLE Order ( 
	Order_ID INT NOT NULL AUTO_INCREMENT, 
	OrderDate Date NOT NULL,
	PRIMARY KEY (Order_ID)
)   ENGINE=INNODB AUTO_INCREMENT= 3 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE TABLE Part ( 
	Part_ID INT NOT NULL AUTO_INCREMENT, 
	UnitCost FLOAT NOT NULL,
	PRIMARY KEY (Part_ID)
)   ENGINE=INNODB AUTO_INCREMENT= 3 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE TABLE XOrderPart ( 
	Order_ID INT NOT NULL,
	Part_ID INT NOT NULL,
	PRIMARY KEY (Order_ID, Part_ID)
	FOREIGN KEY(Order_ID) REFERENCES Order(Order_ID);
	FOREIGN KEY(Part_ID) REFERENCES Part(Part_ID);
)   ENGINE=INNODB AUTO_INCREMENT= 3 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;


PROBLEM:
=========
I want to use the last inserted ID from table Order and the max ID from Part as input parameters into table XOrderPart.
But mySQL throws error when I tried to access LAST_INSERT_ID() and MAX(Part_ID) in the same transaction block:
BEGIN
SET AUTOCOMMIT=0;
START TRANSACTION;
INSERT INTO Order (Customer_ID, OrderDate) VALUES (custId, ordDate);
@newOrderId = SELECT LAST_INSERT_ID();		// mySQL expects END here
@maxPartId = SELECT MAX(Part_ID) FROM Part;	// mySQL expects END here
INSERT INTO XOrderPart(Customer_ID, Part_ID) VALUES (@newOrderId, @maxPartId);
COMMIT;
END
I need all inserts to complete successfully or rollback everything with an error message.

QUESTIONS:
===========
(111) How do I get hold of LAST_INSERT_ID from Order to use as an input parameter in XOrders_Parts?
(222) If the first insert fails, will the transaction crash because the next insert violates foreign key constraints?

Apologies bothering you guys constantly. :)

Options: ReplyQuote


Subject
Written By
Posted
Sproc to Insert Into Multiple Tables
December 14, 2018 01:46AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.