I am very new to creating procedures, looking for some guidance on my code. I cant figure out how to output the number of students being mentored. I am trying to output the following statement: Create a stored procedure called MentoringCount which will display the professor name and the number of students he/she is mentoring. Sort the output by the professor name.
delimiter //
create procedure MentoringCount()
Begin
SELECT p.ProfessorName from professor p
join lab10.student_professor SP
on (S.studentno = SP.studentno)
where SP.mentored = 1
SELECT COUNT (Mentor)
FROM student_professor
order by p.ProfessorName;
END //
Delimiter ;
call mentoredStudents();
student table:
studentno
studentprogram
phoneno
age
firstname
lastname
professor table:
ProfessorId
ProfessorProgram
PhoneNo
Age
ProfessorName
student_professor table:
student_professor_id
ProfessorId
StudentNo
Mentor
There's no difference between doing this query in a stored procedure and normally.
You just need to join the tables and use COUNT(*) along with GROUP BY. Use LEFT JOIN so you'll get zero counts.
delimiter //
CREATE PROCEDURE MentoringCount()
BEGIN
SELECT p.professorName, IFNULL(COUNT(sp.student_professor_id), 0) AS students
FROM professor AS p
LEFT JOIN student_professor AS sp
ON sp.professorID = p.professorID AND sp.Mentored = 1
GROUP BY p.professorID
ORDER BY p.professorName
END;
//
Related
I am newbie to stored procedure, hence this basic question.
I want to create a table of average sales for last 10 days, then I need to query existing stock and update the stock in the sales table.
This create sales data for last 10 days.
DELIMITER //
CREATE PROCEDURE JDSTOCK()
BEGIN
DROP TABLE IF EXISTS Test1;
Create table Test1 AS
Select
Invoice.BranchID,
Invoice.CustomerName,
InvoiceDetail.ProductMasterID,
Sum(InvoiceDetail.Quantity),
Avg(InvoiceDetail.Quantity) As Avg_Quantity,
0.00 As BranchStock
From
Invoice Inner Join
InvoiceDetail On InvoiceDetail.InvoiceID = Invoice.InvoiceID
Where
Invoice.InvoiceDate >= CurDate() - 10 And
Invoice.CustomerName Like '%BRANCH%'
Group By
Invoice.BranchID,
Invoice.CustomerName,
InvoiceDetail.ProductMasterID ;
END;//
DELIMITER;
2. Step that I want to execute from stored procedure
* Create Stock Table for KTMY */
Select
Stock.BranchID,
Stock.ProductMasterID,
Sum(Stock.CurrentQty) As Sum_CurrentQty,
Branch.BranchName,
Max(Stock.PurchaseDate) As Max_PurchaseDate
From
Stock Inner Join
Branch On Branch.BranchID = Stock.BranchID
Where
Branch.BranchName = 'KTMY'
Group By
Stock.BranchID,
Stock.ProductMasterID,
Branch.BranchName
Having
Sum(Stock.CurrentQty) > 0
3. Third step
*** Update stock in sales table
Update DevTest INNER JOIN DevStock on
DevTest.ProductMasterID = DevStock.ProductMasterID
SET DevTest.EKMStock = DevStock.Sum_CurrentQty;
How will I achieve this in stored procedure.
Thanks in advance.
In mySQL stored procedure how can I assign a Query String to a variable, so I can reuse it? In my example I will be using SELECT id FROM audit many times.
CREATE PROCEDURE my_proc()
BEGIN
UPDATE person SET status='Active' WHERE id = (SELECT id FROM audit);
SELECT COUNT(*) FROM (SELECT id FROM audit);
//Multile scenarios the `SELECT id FROM audit` will be used.
END
Something like:
CREATE PROCEDURE my_proc()
BEGIN
myVariable = SELECT id FROM audit;
UPDATE person SET status='Active' WHERE id = (myVariable;
SELECT COUNT(*) FROM (myVariable);
//Multile scenarios the `SELECT id FROM audit` will be used.
END
Is this what you are looking for? Sorry I am not sure what you need.
SELECT #myCount:= count(id) FROM audit;
select #myCount;
Based on your reply, do you need a temporary table to store the ids from the audit and re-use those on the queries?
create temporary table tbl_tmp_audit;
select id from audit;
I am assuming you need this so that you won't join the whole audit columns every time on your succeeding queries.
--first query
UPDATE person AS p
INNER JOIN tbl_tmp_audit t ON p.id = t.id
SET status = 'Active';
--second query
SELECT COUNT(*) FROM tbl_tmp_audit;
Drop temporary table tbl_temp_bookings;
im creating a small hire car system and i want a stored procedure that takes in a date and checks to see which cars are available then. I've got the compare working but if a car has more than one contract and one of the contracts isn't for the entered date but another is it says the car is available. Below is my procedure so far
delimiter //
create procedure allAvailableVehicles(req varchar(15))
BEGIN
select distinct vehicles.vehicleID as "Vehicle ID", vehicles.Make as "Make", vehicles.Model as "Model" from vehicles
left outer join contracts
on vehicles.vehicleID=contracts.vehicleID
where cast(req as date) not between hiredFrom and hiredUntill
or contractID is unknown
order by vehicles.vehicleID;
end
//
delimiter ;
This is a good opportunity to use not exists:
select v.*
from vehicles v
where not exists (select 1
from contracts c
where c.VehicleId = v.VehicleId and
cast(req as date) between hiredFrom and hiredUntil
);
Note: you should not need to cast req as a date, because it should already be stored as a date in the database (unless req also has a time component).
A better way to write the stored procedure is:
delimiter //
create procedure allAvailableVehicles(p_req date)
begin
select v.*
from vehicles v
where not exists (select 1
from contracts c
where c.VehicleId = v.VehicleId and
p_req between hiredFrom and hiredUntil
);
end //
delimiter ;
Use built-in types for date/times. Also, name your parameters to distinguish them from columns.
have a question for you guys,
trying to make a procedure for my mysql table but I need some assistance ...
IM completely block ...
I need to create a procedure that will show the parents name in my table but the table show parents id
ex.
(DELIMITER //
CREATE PROCEDURE fetch_animal_parents (IN animal_id INT, OUT animal_name VARCHAR(10))
BEGIN
DECLARE animal_mom INT DEFAULT 0 ;
DECLARE animal_dad INT DEFAULT 0 ;
DECLARE animal_name_mom VARCHAR(10) ;
DECLARE animal_name_dad VARCHAR(10) ;
SELECT name INTO animal_name, (SELECT name FROM animal WHERE id = child.mother_id) INTO animal_name_mom,
(SELECT name FROM animal WHERE id = child.father_id) INTO animal_name_dad
FROM animal AS child ;
END //)
What im doing wrong ....
................................................................................................
Any input ...
1) why do you select mom/dad's name when you are not using them anywhere?
2) I imagine your procedure should take an child animal id as input and give mom & dad's name as output(that's what you procedure name suggest). In that case you need to either have 2 output value or you need to concatenate those names into 1 variable and return them.
3) #VMai suggested a 2 join format which I would agree. The query will be something like..
SELECT mom.name,dad.name INTO animal_name_mom, animal_name_dad
FROM (select mother_id,father_id from animal where id = <precedure_input>) AS `child`
INNER JOIN (select id,name from animal) AS `mom` ON (mom.id=child.mother_id)
INNER JOIN (select id,name from animal) AS `dad` ON (dad.id=child.father_id)
I see that you have as least tried something on your own (thou very confused). I'd suggest you to start with learning some basic syntax/keyword/functions of mysql before trying procedures. Learn to use GROUP BY, variations of JOIN and you could handle a lot of basic querys.
i'm trying to create an procedure that returns an table with some information of my database, it lists the number of the HOTEL by how many clients used each type of their credit cards on the hotel
Keeping in mind that there is more than 50 hotels and 3 types of credit cards, i want the procedure to run through the data and list then in the table
DELIMITER //
DROP PROCEDURE IF EXISTS `testing` //
CREATE PROCEDURE `testing`(OUT param1 VARCHAR(40))
BEGIN
DECLARE id_cnpjEstabelecimento VARCHAR(40);
DECLARE id_redeCartão VARCHAR(255);
SELECT (cnpjEstabelecimento)
FROM fpcsmovatlantica201308tst04;
SET id_cnpjEstabelecimento := cnpjEstabelecimento;
SELECT (id_redeCartão)
FROM fpcsmovatlantica201308tst04;
SET id_redeCartão := id_redeCartão;
SELECT count(*)
FROM fpcsmovatlantica201308tst04;
WHERE redeCartão like 'id_redeCartão%';
AND cnpjEstabelecimento like 'id_cnpjEstabelecimento%';
END //
DELIMITER ;
An example of an select
SELECT count(*)
FROM fpcsmovatlantica201308tst04
WHERE redeCartão like 'Cielo%'
AND cnpjEstabelecimento like '02223966000466%'
the cnpjEstabelecimento got several values, more than 100+, so it's inviable to make all the selects
I don't even have to use procedures to make it, the final result was
SELECT cnpjEstabelecimento, redeCartão, count(*)
FROM fpcsmovatlantica201308tst04
WHERE redeCartão like 'Cielo%'
GROUP BY cnpjEstabelecimento,redeCartão like 'Cielo%'
ORDER BY cnpjEstabelecimento ASC;
I'm assuming you have one table, which looks kind of like this:
|hotelId|cardType|etc...
I'd go with:
Select hotelId, cardType, count(*)
from myTable
group by hotelId, cardType
I tested it here with the following SQL:
SELECT country, city, count(*)
from customers
group by country, city
ORDER BY Country;