Answer: Stored Functions
Explore how to define and use stored functions within MySQL stored routines. Understand creating local variables, loading query results into variables, and implementing aggregate functions with COALESCE and SUM. Gain skills to write reusable functions for complex queries and optimize data retrieval for advanced interview problems.
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 switches the statement terminator from the default semicolon to$$so that the function body can contain semicolons without prematurely ending theCREATE FUNCTIONstatement.Lines 4–7: The
CREATE FUNCTION fn_customer_total_delivered(p_customer_id INT)definition creates a stored function that accepts a single input parameterp_customer_idof typeINT. TheRETURNS DECIMAL(10,2)clause specifies that the function returns a numeric value with two decimal places. TheDETERMINISTICattribute documents that the function always produces the same result for the samep_customer_id, andREADS SQL DATAstates that the function only reads from tables instead of modifying them.Line 9: The
DECLARE v_total DECIMAL(10,2);statement defines a local variablev_totalinside the function. This variable will hold the aggregated delivered total for the givenp_customer_idbefore it is returned.Lines 11–15: The
SELECT COALESCE(SUM(o.TotalAmount), 0.00)query aggregates theTotalAmountfrom theOrderstable for rows where ...