Answer: Insert Using Stored Procedures
Find a detailed explanation of inserting data in tables using stored procedures in SQL.
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 PROCEDURE
defines a stored procedure calledAddEmployeeWithCategory
with three parameters:EmployeeName
,EmployeeAge
, andProductCategoriesName
.Lines 8–16: The
BEGIN
andEND
are used to define the body of the stored procedure. TheDECLARE
statement creates a variablelastID
to store the ID of the last inserted employee. TheINSERT INTO
statement adds a new row to theEmployees
table with the input parameters. TheSET
statement stores the last inserted employee’s ID inlastID
, andINSERT INTO
statement adds a new row in theProductCategories
table.Line 18: The
DELIMITER ;
resets the statement delimiter back to the default semicolon (;
).Line 21: The
CALL
statement executes the stored procedure, passing'Jane'
,30
...