Error Code 1064 SQL - mysql

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.

Related

SQL stored procedure- where am I going wrong?

I'm trying to create a stored procedure that calculates total revenue from a customer by if it's occupied and the standard rate. I am getting an error message and when I try to call from it I get NULL. Can anyone help? Thanks.
//Delimiter
CREATE PROCEDURE calculateRevenue (in customerIDs int, OUT totalRevenue dec(15,2))
BEGIN
SELECT SUM(Occupied*StandardRate) into totalRevenue FROM climatesouth
WHERE customerIDs = customerID;
END //
delimiter//
call calculateTotal(10, #totalRevenue);
SELECT #totalRevenue;
First you need to give your input parameters different names from the columns. Then you need to use them. Also, DELIMITER goes before the stored procedure definition:
DELIMITER //
CREATE PROCEDURE calculateRevenue (
in in_customerIDs int,
out out_totalRevenue dec(15,2))
BEGIN
SELECT SUM(cs.Occupied cs.* cs.StandardRate) into out_totalRevenue
FROM climatesouth cs
WHERE cs.customerID = in_customerID;
END //
The delimiter assignment is off: your are setting it to // after the create procedure statement.
Also, the parameter name needs to be fixed: your are not using the correct name in the query (your parameter has a trailing 's'), because of which the procedure will not produce the result you expect.
So:
delimiter // -- change the default delimiter here
create procedure calculaterevenue (in p_customerid int, out p_totalrevenue dec(15,2))
begin
select sum(occupied * standardrate) into p_totalrevenue
from climatesouth
where customerid = p_customerid; -- "p_customerid" is the parameter name
end //
delimiter ; -- reset the delimiter, now we can call the procedure
call calculaterevenue(10, #totalrevenue);
select #totalrevenue;
It is easier just to return the result as a result set rather than to use the OUT-parameter. The OUT-parameters are usually used only when calling procedure from another procedure. If you call the procedure from your application, use the result set.
delimiter //
CREATE PROCEDURE calculateRevenue (in_customerID int)
BEGIN
SELECT SUM(Occupied*StandardRate) as totalrevenue
FROM climatesouth
WHERE customerID = in_customerID;
END
//
delimiter ;
call calculateRevenue(10);

MySQL stored procedure syntax error in variables

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 ;

Same query, different outcome

I am trying to run a query which I first typed out like this:
DELIMITER $$
DROP PROCEDURE IF EXISTS development $$
CREATE PROCEDURE development()
BEGIN
DECLARE i INT DEFAULT 1;
WHILE i <= 500 DO
IF NOT EXISTS ((SELECT * FROM customers WHERE customerID = 500)) THEN INSERT INTO customers (firstName) VALUES (''); END IF;
SET i = i + 1;
END WHILE;
END $$
CALL development() $$
DROP PROCEDURE IF EXISTS development $$
DELIMITER ;
but then "compressed" into this:
DELIMITER $$ DROP PROCEDURE IF EXISTS development $$ CREATE PROCEDURE development() BEGIN DECLARE i INT DEFAULT 1; WHILE i <= 500 DO IF NOT EXISTS ((SELECT * FROM customers WHERE customerID = 500)) THEN INSERT INTO customers (firstName) VALUES (''); END IF; SET i = i + 1; END WHILE; END $$ CALL development() $$ DROP PROCEDURE IF EXISTS development $$ DELIMITER ;
on one line. The problem is that the first (multiline) code works, and does what it's supposed to do, while the other (single line) version, doesn't. It doesn't fail or throw errors, it just doesn't insert the rows like the multiline version. Why is this? More importantly, how can I make the single line version work?
Thanks in advance!
please try it this way:
DELIMITER $$
DROP PROCEDURE IF EXISTS development $$ CREATE PROCEDURE development() BEGIN DECLARE i INT DEFAULT 1; WHILE i <= 500 DO IF NOT EXISTS ((SELECT * FROM customers WHERE customerID = 500)) THEN INSERT INTO customers (firstName) VALUES (''); END IF; SET i = i + 1; END WHILE; END $$ CALL development() $$ DROP PROCEDURE IF EXISTS development $$
DELIMITER ;
The last line break might not be neccessary.
But I am fairly confident that, when inlining the whole code you end up setting a delimiter much longe than "$$"
I just executed the completely inlined example on a random sql server of mine and always received a positive result, even though I have not set up the related db structure.
with line breaks there are complaints about missing tables (as would be expected)
Regards
Stefan
You cannot run any SQL on the same line as delimiter. delimiter is a built in mysql client command that sets the statement seperator, not an sql interpreter. It takes one argument, read up to the first space or newline. Everything else is ignored.
delimiter $$ select now() $$
No output, because everything after $$ is thrown away.
Or illustrated by bad syntax
delimiter "$$" select; nothing order by from nowhere group , oh forget it $$

MySQL stored procedure troubles

Basically i'm going to run this procedure anytime a student enrolls/drops a course.
I'm trying to set student_total = # of students in a course, then update that corresponding section with (student_total + 1) i'm having trouble finding good documentation for stored procedures. I'm getting an error on my Declare student_total int; line. What am i not doing correct?
DELIMITER $$
CREATE PROCEDURE `mydb`.`update_seats` (IN section_ID varchar(20))
BEGIN
SET #section_id=section_id;
DECLARE student_total int;
-- count the number of students in the course --
SET student_total = SELECT count(student_ID) from course
WHERE section_ID = #section_id;
Update Section SET students_enrolled = (student_total + 1)
WHERE section_ID = #section_id;
END
Problems
Error 1
From MySql documentation:
DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.
So, you should move DECLARE... statement before the SET #section_id... statement.
Error 2
You are trying to select a value into a variable using invalid snytax! You should use SELECT ... INTO instead of SET ... = SELECT ... (which is invalid syntax).
Removing Redundancy
No need to assign parameter (section_ID) to a global variable (#section_ID). You can simply change the parameter name to avoid name collision with section.section_ID column.
Solution
DELIMITER ;;
CREATE PROCEDURE `update_seats` (IN p_section_ID VARCHAR(20))
BEGIN
DECLARE student_total INT;
SELECT count(student_ID)
INTO student_total
FROM course
WHERE section_ID = p_section_ID;
UPDATE section
SET students_enrolled = (student_total + 1)
WHERE section_ID = p_section_ID;
END;;
DELIMITER ;
You're using the command line tool, yes?
It would be helpful to know the error message you received but based off the code you posted I don't see where you reset the delimiter command after the BEGIN...END block.
Taken from http://dev.mysql.com/doc/refman/5.1/en/stored-programs-defining.html

Getting errors when trying to create a PROCEDURE in mysql

I am trying to create a mysql stored procedure, but I get this error:
Script line: 2 Failed to CREATE PROCEDURE proc_test_bideep
The stored procedure code is:
DELIMITER $$
DROP PROCEDURE IF EXISTS `commun`.`insert_categorie` $$
CREATE PROCEDURE `commun`.`insert_categorie` (id_mere INT,
lib_categ VARCHAR(50),
id_categ_sup INT ,
categ_authInstantBuy INT)
BEGIN
SET #bg_mere := (SELECT categ_bg FROM categ_basic WHERE categ_id = id_mere);
#bg_mere+2,categ_level_bideep,categ_statut,categ_adult,categ_authSmallBid,categ_authBid,categ_authInstantBuy);
SELECT '1' AS code_retour; END IF;
ecetera.........
END $$
DELIMITER ;
a) You need to DECLARE any variables on the first lines of the procedure, including their datatype:
DECLARE bg_mere INT;
b) To fetch a value from the database into a variable, you use SELECT ... INTO syntax:
SELECT categ_bg INTO bg_mere FROM categ_basic WHERE categ_basic.categ_id = id_mere;
c) You have an END IF without the corresponding IF.
d) The closing END needs a semicolon (not BEGIN though), only then do you need a delimiter to finish the entire statement, and finally you should reset the delimiter back to normal:
BEGIN
# body of the stored procedure goes here
END;
$$
DELIMITER ;
Your parameters are missing the keyword IN such as: ...(IN id_mere INT, IN lib_categ ...). Also, you need to configure your OUT variable for #bg_mere in the initial parameter list such as (IN xxx, ..., OUT bg_mere VARCHAR/INT/WHATEVER).