I have table group with begindate lesson count and weekdays columns. I would like write MySQL procedure for adding data to another table named lessons according to group. But I couldn't handle with syntax of MySQL. Could you please help me resolve problems with that procedure:
CREATE PROCEDURE simpleproc (IN idGroup INT, IN groupName varchar(20),IN beginDate date, IN weekday1 INT, IN weekday2 INT, IN lessonCount INT)
BEGIN
DECLARE i;
SET i:=1;
WHILE i<=lessonCount DO
DATE_ADD(beginDate,INTERVAL 1 DAY)
IF (WEEKDAY(beginDate)=weekday1) OR (WEEKDAY(beginDate)=weekday2) THEN
SET name:=groupName+i;
SET price:=DIV(price,8)
insert into lessons (lessonName, idGroup, lessonPrice, datePassed)
values (name,idGroup,price,begindate);
SET i:=i+1
END IF;
END WHILE;
END
After solving problems I will add this code to prepared statement in Java
This will run. Make sure: 1. That you increment i in a proper place of your code inside the while loop. 2. Avoid usind reserved words (like name) for fields and variables. 3. Define price variable somewhere before making integer division of it. You know the code and your tables' structure. Nobody is capable to do it for you.
DROP PROCEDURE IF EXISTS `simpleproc`;
DELIMITER ;;
CREATE DEFINER=`root`#`localhost` PROCEDURE `simpleproc`(IN idGroup INT, IN groupName varchar(20),IN beginDate date, IN weekday1 INT, IN weekday2 INT, IN lessonCount INT)
BEGIN
DECLARE i int;
DECLARE name1 int;
DECLARE price int;
SET i:=1;
WHILE i<=lessonCount DO
SET beginDate:=DATE_ADD(beginDate,INTERVAL 1 DAY);
IF WEEKDAY(beginDate) in(weekday1,weekday2) THEN
SET name1:=groupName+i;
SET price:=price DIV 8;
insert into lessons (lessonName, idGroup, lessonPrice, datePassed)
values (name1,idGroup,price,begindate);
END IF;
SET i:=i+1;
END WHILE;
END
;;
DELIMITER ;
Related
I have a problem with a Trigger and a Procedure in MySQL, the exercises track is:
Define a Trigger that delete automatically visits of patients that in the last year they did only the preliminer visit.
This is the SQL code created from me:
CREATE TRIGGER EliminaVisitePreliminari
AFTER INSERT ON Visita
FOR EACH ROW
BEGIN
IF(EXISTS(
SELECT Vis.ID_Visita
FROM Visita AS Vis, Preliminare AS Pre
WHERE Vis.ID_Visita=Pre.ID_Visita
AND DATEDIFF(CURRENT_DATE(), Vis.Data)>365
GROUP BY Vis.ID_Visita)) THEN
DELETE FROM Visita
WHERE ID_Visita=(
SELECT Vis.ID_Visita
FROM Visita AS Vis1, Preliminare AS Pre1
WHERE Vis1.ID_Visita=Pre1.ID_Visita
AND DATEDIFF(CURRENT_DATE(), Vis.Data)>365
); # Error here
END IF; # Here
END; # And here
And this for Procedure:
Define a schedulated procedure that, every ending's month, calculates automatically the amount of every month's interventions, showing the percentage not yet sold
SQL created from me:
CREATE PROCEDURE TotInterventiSettimanali(OUT Cont INT, SomTot INT, Saldare DECIMAL)
BEGIN
DECLARE Costo INT; # Error here
DECLARE DaSald DECIMAL; # Here
DECLARE Cont INT; # Here
SELECT COUNT(*), SUM(Vis.Parcella), AVG(Vis.Parcella) INTO Cont, SomTot, Saldare
FROM Visita AS Vis, Intervento AS Inerv
WHERE MONTH(Vis.Data)=MONTH(CURRENT_DATE())
AND Vis.ID_Visita=Interv.ID_Visita;
END; # And here
Help me please.. Thanks a lot!
MySQL treats everything ending with ";" as command. To create functions, procedures and triggers, you have to change the delimiter to something else, input the text and change the delimiter back. For example, in your case:
DELIMITER //
CREATE PROCEDURE TotInterventiSettimanali(OUT Cont INT, SomTot INT, Saldare DECIMAL)
BEGIN
.......
END;
//
DELIMITER ;
Note the delimiter // after procedure text.
I have stored procedure. How I can call this procedure taking data from different table. idGroup is column name from different table.
DROP PROCEDURE IF EXISTS `simpleproc`;
DELIMITER ;;
CREATE DEFINER=`sa`#`192.168.1.253` PROCEDURE `simpleproc`(IN idGroup INT, IN groupName varchar(20),IN beginDate date, IN weekday1 INT, IN weekday2 INT, IN lessonCount INT)
BEGIN
DECLARE i int;
DECLARE name1 int;
DECLARE price int;
SET i:=1;
WHILE i<=lessonCount DO
SET beginDate:=DATE_ADD(beginDate,INTERVAL 1 DAY);
IF WEEKDAY(beginDate) in(weekday1,weekday2) THEN
SET name1:=groupName+i;
SET price:=price DIV 8;
insert into lessons (lessonName, idGroup, lessonPrice, datePassed)
values (name1,idGroup,price,begindate);
END IF;
SET i:=i+1;
END WHILE;
END
;;
DELIMITER ;
Let's see if I can edit this and put the whole procedure in.
I am trying to convert an Oracle database to MySQL. I have all the tables, keys, indexes, and views converted. I now need to convert a stored procedure to MySQL.
I have most of it done, and there is only one hang up on my code:
set dns1_tmp = X.X.X.X;
SET dns2_tmp = X.X.X.X;
This gives me an error of 1064 Syntax Error: Missing semicolon
I have tested the rest of my procedure, and it works fine. It creates it, runs it, and retrieves data from it, but only if I remove those two lines.
Any ideas on what I can do?
Whole stored procedure:
DELIMITER //
USE `TEST`//
DROP PROCEDURE IF EXISTS `proc_IN`//
CREATE DEFINER=`root`#`localhost` PROCEDURE `proc_IN`
(IN DNIS VARCHAR(20),
IN MSISDN VARCHAR(20),
IN AVPAIR1 VARCHAR(20),
IN AVPAIR2 VARCHAR(20),
IN GROUPID VARCHAR(20),
OUT DNS1 VARCHAR(15),
OUT DNS2 VARCHAR(15),
OUT AUTHSTAT VARCHAR(100))
BEGIN
declare dns1_tmp varchar(15);
declare dns2_tmp varchar(15);
set dns1_tmp = X.X.X.X;
SET dns2_tmp = X.X.X.X;
DECLARE avpair1_tmp varchar(15);
DECLARE avpair2_tmp varchar(15);
DECLARE grpid_tmp varchar(15);
DECLARE C_USER CURSOR FOR SELECT AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID FROM GRP, ALLMEMBER WHERE ALLMEMBER.GROUPID=GRP.GROUPID
UNION
SELECT AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID FROM GRP;
OPEN C_USER;
FETCH C_USER INTO AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID;
LOOP
FETCH C_USER INTO avpair1_tmp, avpair2_tmp, dns1_tmp, dns2_tmp, grpid_tmp;
INSERT INTO duplog VALUES(DNIS, MSISDN, avpair1_tmp, avpair2_tmp, dns1_tmp,dns2_tmp, grpid_tmp, SYSDATE);
END LOOP;
IF C_USER%ROWCOUNT > 1 THEN
INSERT INTO duplog VALUES(DNIS, MSISDN, AVPAIR1, AVPAIR2, DNS1,DNS2, GROUPID, SYSDATE);
SET AUTHSTAT := 'ok';
elseif C_USER%ROWCOUNT = 1 THEN
SET AUTHSTAT := 'ok';
ELSE
SET AUTHSTAT := NULL;
END IF;
CLOSE C_USER;
COMMIT;
END //
DELIMITER ;
This question already has answers here:
How To have Dynamic SQL in MySQL Stored Procedure
(3 answers)
Closed 8 years ago.
is it possible to set a variable to an insert statement in a stored procedure?
Something like:
set variable1 = insert into table(field1, field2, field3) values(val1, val2, variable2);
If so, how should it be written?
I keep throwing errors and documentation in the wild is inconclusive.
I was going for brevity but the entire procedure is thus:
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `new_accession`(in barcode int, in accepted varchar(11), in wt float(11,2), in wtunit varchar(3),in draw date, in chist varchar(256), in ghist varchar(256), in meds varchar(256), in diffdiag varchar(256),in diseasesus varchar(256),in volume int, in facility int, in patient int, in employ int, in compromised int, in receiving int, in test int)
BEGIN
declare accessionId int;
declare accessionTest int;
declare tkInsert varchar(256);
declare hptInsert varchar(256);
declare calInsert varchar(256);
declare pthInsert varchar(256);
declare vitdtkInsert varchar(256);
declare cnpInsert varchar(256);
if wtunit = 'lb' then set wt = convertLbKg(wt);
end if;
INSERT INTO accession(barcode_accession,accepted_accession,weight_accession,req_weight_units,draw_date_accession,cancer_history_accession,general_history_accession,medication_accession,differential_diagnosis_accession,disease_suspect_accession,volume_accession,facility_doctor_index_id_facility_doctor_index,patient_id_patient,employee_id_employee,accession_compromised_id_accession_compromised,receiving_id,accession_typeof_id_accession_typeof)
VALUES (barcode,accepted,wt,wtunit,draw,chist,ghist,meds,diffdiag,diseasesus,volume,facility,patient,employ,compromised,receiving,1);
set accessionId = last_insert_id();
set tkInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,1,'Pending');
set hptInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,2,'Pending');
set calInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,3,'Pending');
set pthInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,4,'Pending');
if test = 1 then tkInsert,calInsert;
elseif test =2 the hptInsert,pthInsert;
else pthInsert;
end if;
END
It is not very clear what you want but if your goal is to store insert's outcome (affected rows) you could use ROW_COUNT().
ROW_COUNT() returns the number of rows changed, deleted, or inserted
by the last statement if it was an UPDATE, DELETE, or INSERT.
For other statements, the value may not be meaningful.
For example:
variable1 = (select ROW_COUNT());
I think you're looking for prepared statements.
PREPARE tkInsert FROM CONCAT("insert into pending(accession_facility_index,reagent_type,`status`)values(?, 1,'Pending')";
Then you execute it with:
EXECUTE tkInsert USING accessionId;
I have a little problem. Looks like the procedure does not exist. Somehow it's dropped after the creation. I get different error each time i change something. I'm not really sure what's causing the error, maybe I'm not allowed to drop procedures and creating them in the same query.
I hope you guys can help me out.
drop procedure if exists refIntChk;
DELIMITER //
CREATE PROCEDURE refIntChk(IN district INT(11), OUT b INT(1))
BEGIN
DECLARE b INT(1);
IF district IN (select dist FROM t13)
THEN
SET b = 1;
ELSE
SET b = 0;
END IF;
END; //
DELIMITER ;
drop procedure gen if exists ;
DELIMITER //
CREATE PROCEDURE gen()
BEGIN
DECLARE rows INT(11) DEFAULT (SELECT COUNT(dist) FROM t13);
DECLARE district INT(11);
DECLARE custname VARCHAR(16);
DECLARE revenue FLOAT;
DECLARE x INT DEFAULT 10000;
DECLARE outvar INT(11);
WHILE x > 0
DO
SET district = FLOOR(RAND()*rows)+1;
CALL refIntChk(district, outvar);
IF outvar = 1
THEN
SET custname = substring(MD5(RAND()), -16);
SET revenue = (RAND() * 10);
INSERT INTO t14 VALUES(NULL, custname, district, revenue);
SET x = x - 1;
END IF;
END WHILE;
END;//
DELIMITER ;
CALL gen();
When you get errors, it's usually good to run each statement, one by one, and see which one is producing the error.
The second DROP procedure statement should be:
drop procedure if exists gen;