Answer: Update Using Stored Procedures
Find a detailed explanation of updating records using stored procedures in SQL.
Solution
The solution is given below:
-- Query to update records using stored procedureDELIMITER $$CREATE PROCEDURE DiscountCategoryProducts(IN catID INT,IN discountPercentage DECIMAL(5, 2))BEGINUPDATE Products AS PSET P.Price = P.Price * (1 - discountPercentage / 100)WHERE P.CategoryID = catID;END $$DELIMITER ;-- Execute stored procedureCALL DiscountCategoryProducts(1, 10);-- View the resultSELECT * FROM Products P WHERE P.CategoryID = 1;
Code explanation
The explanation of the solution code is given below:
Line 2: The
DELIMITER $$
changes the statement delimiter to$$
so semicolons can be used within the procedure.Lines 4–5: The
CREATE PROCEDURE
defines a stored procedure calledDiscountCategoryProducts
with two parameters:catID
anddiscountPercentage
.Lines 6–10: The
BEGIN
andEND
are used to define the body of the stored procedure. TheUPDATE
statement updates the existing record in theProducts
table with new values for prices.Line 12: The
DELIMITER ;
resets the statement delimiter back to the default semicolon (;
).Line 15: The
CALL
statement executes the stored procedure, passing1
and10
as ...