Answer: Execution Blocks
Explore how to use execution blocks within stored procedures and triggers to manage complex SQL logic. Understand delimiter usage for defining routines, the difference between execution blocks and transactions, and how triggers update data automatically during table modifications. This lesson equips you with practical skills to create, execute, and troubleshoot execution blocks in advanced SQL scenarios.
We'll cover the following...
Solution
The solution is given below:
Explanation
The explanation of the solution code is given below:
Line 2: The
DELIMITER //command sets a temporary delimiter so that semicolons withinBEGIN ... ENDblocks do not prematurely terminate the routine definitions. This is essential when defining stored procedures or triggers in MySQL.Lines 4–9: A stored procedure
GetTotalStockValueis created using an execution block.DECLARE total_value DECIMAL(10,2);defines a local variable to hold the result.SELECT SUM(Price * Stock) INTO total_value FROM Products;calculates the total inventory value across all rows.SELECT total_value AS TotalStockValue;returns the value to the caller.The block ends with
END //using the custom delimiter.
Lines 12–19: A trigger
UpdateRestockDateis defined to run before any update on theProductstable.FOR EACH ROWensures the logic runs individually for every modified row.Inside the execution block,
IF NEW.Stock <>...