Answer: Insert Using Stored Procedures
Understand how to create and use stored procedures in SQL for inserting data across related tables. Explore parameterized procedures, variable declaration, and multiple insert statements. This lesson also covers alternatives like triggers, user-defined functions, and prepared statements to manage data insertion tasks.
Solution
The solution is given below:
Code explanation
The explanation of the solution code is given below:
Line 3: The
DELIMITER $$changes the statement delimiter to$$so semicolons can be used within the procedure.Lines 5–7: The
CREATE PROCEDUREdefines a stored procedure calledAddEmployeeWithCategorywith three parameters:EmployeeName,EmployeeAge, andProductCategoriesName.Lines 8–16: The
BEGINandENDare used to define the body of the stored procedure. TheDECLAREstatement creates a variablelastIDto store the ID of the last inserted employee. TheINSERT INTOstatement adds a new row to theEmployeestable with the input parameters. TheSETstatement stores the last inserted employee’s ID inlastID, andINSERT INTOstatement adds a new row in theProductCategoriestable.Line 18: The
DELIMITER ;resets the statement delimiter back to the default semicolon (;).Line 21: The
CALLstatement executes the stored procedure, passing'Jane',30...