I need help creating this particular stored function and call it by using the single select statement. Below are the questions with my answer. I think I got the first part right but I'm not sure. Any suggestions/advice? For the second question (part b), I'm calling the function incorrectly and can't get it to appear as specified in question/part b. Any advice? I would really appreciate the assistance.
Part A) Create a stored function called get_customer_balance which will return a customer’s balance from the membership table by passing in a membership number.
My Answer:
DELIMITER $$
CREATE FUNCTION get_customer_balance (membershipNo INT)
RETURNS dec
DETERMINISTIC
BEGIN
DECLARE CustBal dec;
SET CustBal = 0;
SELECT balance INTO CustBal
FROM membership
WHERE membership_id = membershipNo;
RETURN CustBal;
END$$
DELIMITER ;
Membership Table. This is the original table of the problem (for reference guide)
create table membership
( membership_id int primary key,
balance decimal(10,2) not null
);
insert membership(membership_id,balance) values (1,1),(102,11),(103,109.25);
select membership_id,format(get_customer_balance(membership_id),2) as theBalance
from membership
where membership_id=102;
+---------------+------------+
| membership_id | theBalance |
+---------------+------------+
| 102 | 11.00 |
+---------------+------------+
Mysql Manual page on Create Proc and Functions
Calling your user defined function (UDF) would be like calling any built-in function. Even if it involved joins on tables with aliases (which the above does not show).
A much better example would be one in which there are two tables. A membership
table, and a transaction
table that needs summed. But that wasn't your schema.
Would you like to see such a thing?