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 ;
Part B question
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?
Related
I'm trying to write a stored procedure in MySQL and then call it back, and I have to submit a screenshot of the procedure returning a correct response. The code for storing the procedure seems to work fine (no errors, at least), but when I run the CALL function it returns 0.00 no matter which number I put in for #column3. My instructor thinks the issue is stating the OUT as AmountDue before I define the variable at the very top, but I couldn't figure out another way to have an input for #column3 in the CALL function without the IN/OUT constraints. I'm very new at this, obviously, so forgive me if I'm missing something obvious...Anyone got any ideas?
Also, I don't need any help with building the database, adding tables, anything like that. The database exists and functions appropriately. Only need help on storing the procedure and calling it back. Thanks.
delimiter //
DROP PROCEDURE IF EXISTS GetAmountDue;
CREATE PROCEDURE GetAmountDue(IN order_num INT, OUT AmountDue DECIMAL(10,2))
BEGIN
DECLARE AmountDue DECIMAL(10,2) DEFAULT 0;
SELECT COST
INTO #AmountDue
FROM cake_shape
INNER JOIN ll_cakery.order
ON cake_shape.shape_id=order.shape_id
WHERE order_num=#order_num;
SELECT AmountDue;
END//
delimiter ;
CALL GetAmountDue('113',#AmountDue);
order_num is a column with individual 3-character integer data values
cost is a column with individual decimal(10,2) data values
cake_shape is a table
ll_cakery.order is a table (that doesn't work quite right because
mysql has a command ORDER so I have to give the schema name)
shape_id is a column, only used in the procedure for the join
in the CALL function, #order_num=113
You are passinf a string not an int
You don't compare column 3 with column1
Last you have to set the output variable with the data ou get from the select
Last never name variables like columns name, that brings only problems
CREATE tABLE table1 ( COST DECIMAL(19,2),column2 int, column3 int)
INSERT INTO table1 VALUES (10.2,1,1),(10.2,1,1)
CREATE TABLE table2 (column2 int)
INSERT INTO table2 VALUES (1)
CREATE PROCEDURE GetAmountDue(IN _column1 INT, OUT _AmountDue DECIMAL(10,2))
BEGIN
SELECT SUM(COST)
INTO #AmountDue
FROM table1
INNER JOIN table2
ON table1.column2=table2.column2
WHERE column3=_column1;
SET _AmountDue := #AmountDue;
END
CALL GetAmountDue(1,#AmountDue);
SELECT #AmountDue
| #AmountDue |
| ---------: |
| 20.40 |
db<>fiddle here
I have a table and its columns are id(int), order_id(int), partner_id(int)
Now I want to increment order_id based on partner_id ,
For Example
for partner 1, order_id's are 1,2,3
then if partner 2 is placing the order, the order_ids should start again from 1 and not from 4.
What is the best way to do so in mysql ? Should I read the last order id for a particular partner from db every time I want to create a new order ?
I am using mysql and sequelize
In a similar scenario for my case I 1st created a column on the order table called order_number.
Then created a mysql function to get the expected order_number base on parameter of the function and the order table.
Then on insert I just called the mysql function with appropriate parameter.
Here is what the mysql function looked like in my case:
Creating the function:
DELIMITER $$
CREATE FUNCTION `get_order_number`(partner_id VARCHAR(255)) RETURNS int(10)
BEGIN
DECLARE getCount INT(10);
SET getCount = (
SELECT COUNT(id)
FROM order_table
WHERE `partner_id` = partner_id
) + 1;
RETURN getCount;
END$$
DELIMITER ;
.
.
Implementation:
INSERT INTO (
id,
order_id,
pertner_id
) VALUES (
NULL,
get_order_number(10), -- 10 is partner_id
10 -- 10 is partner_id
);
.
.
Explanation of the function
1st pass partner_id as parameter for the function.
2nd inside the function I created a select query to get the number of how many orders have this partner created.
Finally adding one (1) with the returned number to get the last value.
.
.
Declaimer:
I have been using this function for over 3 years and have not got any issues yet. But this function has a weak point: When I submit the form simultaneously in two form/page at the same time (in millisecond) I get a deadlock error error for calling same function at the same time. Since I have moderate users I have not faced this error yet in real life situation.
I am using this function in plain mysql driver with node js, have not tested with sequelize.
Hope this helps.
i make this simple STORED FUNCTION in MySql that returns emails sparated with comma:
CREATE FUNCTION get_participantes (id INT) RETURNS VARCHAR(50)
BEGIN
DECLARE par VARCHAR(50) DEFAULT "";
(select GROUP_CONCAT(mail SEPARATOR ',') INTO #par from users where id IN (
select user_id from meeting_participants where meeting_id = id));
RETURN #par;
END
But when i call it using SELECT, i got NULL everytime. The SQL sentence works perfectly but itself.
+----------------------+
| get_participantes(5) |
+----------------------+
| NULL |
+----------------------+
Please help
The name of your function parameter is id, but you also have a column id in your users table, and maybe there's an id column in your meeting_participants table as well.
This creates an ambiguity. The expression doesn't know whether you mean the column id or the function parameter id.
You should give your function parameter a distinct name, to resolve the ambiguity.
CREATE FUNCTION get_participantes (_id INT) RETURNS VARCHAR(50)
READS SQL DATA
BEGIN
DECLARE par VARCHAR(50) DEFAULT "";
(select GROUP_CONCAT(mail SEPARATOR ',') INTO par from users where id IN (
select user_id from meeting_participants where meeting_id = _id));
RETURN par;
END
A couple of other issues that you should know about, even though they are not related to your question:
In MySQL routines (unlike SQL Server for example), your par local variable is not the same as the #var session variable. Your code in this specific case will work, but it's possible some other function you write will be confused. See also my answer to "#" symbol in stored procedure?
You should add the clause READS SQL DATA to your function, or else you may get this error (as I did when I tested your function):
ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)
I have been sreaching around and I could not find an answer to this question. It may be very simple or it could a bug, so any help to point out what I am doing wrong, it's appreciated in advance.
I have a table where id is unique:
Table school
---------------------------
id name class fitness
---------------------------
1 Joe 4 healthy
2 Alice 7 good
3 Bob 10 excellent
and the stored procedure is:
CREATE PROCEDURE checkid(IN ID INT)
BEGIN
SELECT * FROM school WHERE id = ID;
END
executing the above procedure with following command:
CALL checkid(2)
returns the entire table. if I changed the SELECT statement to:
CREATE PROCEDURE checkid(IN ID INT)
BEGIN
SELECT * FROM school WHERE id = ID LIMIT 1;
END
I get the first row of table as the return value like this which is wrong.
id name class fitness
---------------------------
1 Joe 4 healthy
how can I fix this?
I think you are doing something wrong with database schema or procedure name or your query or stored procedure in not saved correctly.
Try to create your procedure in by setting your default schema in workbench and then run it.
But I do think this is not possible at all.
Thanks everyone for your help. after trying many different things and further search through the net. I found this link that help to resolve the issue.
How to get a row by ID in a MySQL Stored Procedure?
when I changed the input parameter name to something else, it worked.
Is there any way to automatically find out the returned column names of a stored procedure and their data types?
Assuming my stored procedure is as follows:
CREATE PROCEDURE `user_countries`()
BEGIN
select m.ID, m.Name, c.Country
from Member AS m, Country AS c
where m.CountryId = c.ID;
END$$
This returns me a table which looks like this:
ID | Name | Country
-------------------------
1 John USA
2 Mary Australia
I need to be able to query my stored procedure so that I can see something like the following
ColName | Data Type
------------------------
ID | INT
Name | Varchar(50)
Country | Varchar(50)
I have not heard of anything that can be done for a stored procedure similar to the table equivalent of
describe Member;
Any suggestions?
PS. This is just a trivial example, I have hundreds of tables and hundreds of stored procedures of varying complexity which I need to analyze.
ANSWER
Thanks to #BishnuPaudel from the comments below.
I am connecting to the db via c# .net so the approach was to query the data which was returned from the stored procedure rather than accessing it via mysql commands.
Using the example from the msdn library
http://msdn.microsoft.com/en-us/library/system.data.datatable.columns(v=vs.110).aspx
I have added the column.DataType print statement to see the Datatypes of the column.
private void PrintValues(DataTable table) {
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.WriteLine(column.DataType);
Console.WriteLine(row[column]);
}
}
}
Thanks again.