Answer: Insert Using Stored Procedures
Find a detailed explanation of inserting data in tables using stored procedures in SQL.
We'll cover the following...
Solution
The solution is given below:
-- Query with stored procedure named AddEmployeeWithCategory-- and parameters are EmployeeName, EmployeeAge, and ProductCategoriesNameDELIMITER $$CREATE PROCEDURE AddEmployeeWithCategory (IN EmployeeName VARCHAR(50),IN EmployeeAge INT,IN ProductCategoriesName VARCHAR(50) )BEGINDECLARE lastID INT;INSERT INTO Employees (EName, Age)VALUES (EmployeeName, EmployeeAge);SET lastID = LAST_INSERT_ID();INSERT INTO ProductCategories (CategoryName, EID)VALUES (ProductCategoriesName, lastID);END $$DELIMITER ;-- Execute the stored procedureCALL AddEmployeeWithCategory('Jane', 30, 'Jackets');-- Show the recently added dataSELECT E.EName, E.Age, C.CategoryNameFROM Employees EJOIN ProductCategories C ON E.EID = C.EIDWHERE E.EName = 'Jane';
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...