Error 1064 declaring variable inside trigger - mysql

I'm having trouble declaring a variable inside a trigger.
SET DELIMITER ;;
BEGIN
DECLARE qtyNow INT;
SET qtyNow = (
SELECT qty
FROM warehouse
WHERE bin_id = 'GA66'
);
DECLARE need INT;
SET need = (
SELECT min_level
FROM warehouse
WHERE bin_id = 'GA66'
);
END;;
SET DELIMITER ;
I get error #1064 which means illegal syntax. I don't see where I went wrong. I even removed all that bulk and just had
DECLARE qtyNow INT;
And this single line still pops the error.

I see two problems.
One, you have a BEGIN...END block but you are not declaring a trigger.
https://dev.mysql.com/doc/refman/5.7/en/begin-end.html says:
BEGIN ... END syntax is used for writing compound statements, which can appear within stored programs (stored procedures and functions, triggers, and events).
You can't use BEGIN...END as a bare statement. It must be part of a CREATE TRIGGER, CREATE PROCEDURE, CREATE FUNCTION, or CREATE EVENT.
Two, you have two DECLARE statements in your block, with a SET in between.
https://dev.mysql.com/doc/refman/5.7/en/declare.html says:
DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.
You are trying to use a second DECLARE after you have done another statement, SET. Do all your DECLAREs up front.

Related

MySQL Stored Procedure - if then not functioning

I'm converting SQL Server stored procedures to MySQL and running into issues. I have a stored procedure with an IF THEN ELSE that, while not giving errors, is not returning any data either and I'm not seeing the problem to fix it. The queries by themselves are correct and return data but don't seem to work in the stored procedure. This is a simplified version of the real query just FYI.
The SQL for creating the stored procedure is:
DROP PROCEDURE IF EXISTS `sp_GetVolunteerAwardsList`;
DELIMITER //
CREATE PROCEDURE `sp_GetVolunteerList`( IN glAward_in int)
BEGIN
DECLARE glAward_In INT;
DECLARE awardType_In varchar(100);
DECLARE awardActive INT;
IF (glAward_In) = 0 THEN
SELECT * FROM tbl_volunteer
ELSEIF (glAward_In) = 1 THEN
SELECT * FROM tbl_volunteerpositions
END IF;
END
//
As always, any assistance would be most appreciated.
Check the glAward_In parameter or variable.
The SP is receiving the parameter glAward_in, i in lower case.
Then there is a DECLARE that declares a different variable glAward_In, i in upper case.
The if is done using the glAward_In in uppercase which is not set in any place of the SP. And the parameter in lower case is not used anywhere in the SP.
I think you have to remove the DECLARATION of the variable in upper case, and use the parameter in lowercase for the IF evaluation.

Call a stored procedure from the DECLARE statement when using cursors in MySQL

I am trying to use a cursor in MySQL to call a stored procedure many times. I want to call it as many times as a value for my_id exists in some temporary table, and iterate through those ids and concatenate the results.
Anyway, I'm having trouble with this part of the process:
DECLARE curs CURSOR FOR
SELECT something FROM somewhere;
I don't want to select something from somewhere. I want something like
DECLARE curs CURSOR FOR
CALL storedproc(#an_id);
Can the DECLARE statement be used to call a stored procedure? Or does it have to be associated with a SELECT only? Googling around, I'm afraid that the latter is the case.
Using a cursor requires some standard boilerplate code to surround it.
Using a cursor to call a stored procedure for each set of values from the table requires essentially the same boilerplate. You SELECT the values you want to pass, from wherever you're getting them (which could be a temporary table, base table, or view, and can include calls to stored functions) and then call the procedure with those values.
I've written an syntactically valid example of that boilerplate code, below, with comments to explain what each component is doing. There are few things I dislike more than being asked to just do something "just because" -- so everything is (hopefully) explained.
You mentioned calling the procedure with multiple values, so this example uses 2.
Note that there events that happen her are in a specific order for a reason. Variables have to be declared first, cursors have to be declared before their continue handlers, and loops have to follow all of those things. This gives an impression that there's some fairly extreme inflexibility, here, but that's not really the case. You can reset the ordering by nesting additional code inside BEGIN ... END blocks within the procedure body; for example, if you needed a second cursor inside the loop, you'd just declare it inside the loop, inside another BEGIN ... END.
DELIMITER $$
DROP PROCEDURE IF EXISTS `my_proc` $$
CREATE PROCEDURE `my_proc`(arg1 INT) -- 1 input argument; you might not need one
BEGIN
-- from http://stackoverflow.com/questions/35858541/call-a-stored-procedure-from-the-declare-statement-when-using-cursors-in-mysql
-- declare the program variables where we'll hold the values we're sending into the procedure;
-- declare as many of them as there are input arguments to the second procedure,
-- with appropriate data types.
DECLARE val1 INT DEFAULT NULL;
DECLARE val2 INT DEFAULT NULL;
-- we need a boolean variable to tell us when the cursor is out of data
DECLARE done TINYINT DEFAULT FALSE;
-- declare a cursor to select the desired columns from the desired source table1
-- the input argument (which you might or might not need) is used in this example for row selection
DECLARE cursor1 -- cursor1 is an arbitrary label, an identifier for the cursor
CURSOR FOR
SELECT t1.c1,
t1.c2
FROM table1 t1
WHERE c3 = arg1;
-- this fancy spacing is of course not required; all of this could go on the same line.
-- a cursor that runs out of data throws an exception; we need to catch this.
-- when the NOT FOUND condition fires, "done" -- which defaults to FALSE -- will be set to true,
-- and since this is a CONTINUE handler, execution continues with the next statement.
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- open the cursor
OPEN cursor1;
my_loop: -- loops have to have an arbitrary label; it's used to leave the loop
LOOP
-- read the values from the next row that is available in the cursor
FETCH NEXT FROM cursor1 INTO val1, val2;
IF done THEN -- this will be true when we are out of rows to read, so we go to the statement after END LOOP.
LEAVE my_loop;
ELSE -- val1 and val2 will be the next values from c1 and c2 in table t1,
-- so now we call the procedure with them for this "row"
CALL the_other_procedure(val1,val2);
-- maybe do more stuff here
END IF;
END LOOP;
-- execution continues here when LEAVE my_loop is encountered;
-- you might have more things you want to do here
END $$
DELIMITER ;
Can the DECLARE statement be used to call a stored proc?
Not possible and documentation is pretty clear on that
Cursor DECLARE Syntax
This statement declares a cursor and associates it with a SELECT statement that retrieves the rows to be traversed by the cursor. To fetch the rows later, use a FETCH statement. The number of columns retrieved by the SELECT statement must match the number of output variables specified in the FETCH statement.

MySQL - Storing variables inside CREATE FUNCTION

I'm trying to figure out how to store variables inside a function in mySQL. I am trying to create a function that capitalizes a field name. Creating a function works if I don't create variables. The problem is this is difficult to read, and is easy to make mistakes with.
CREATE FUNCTION capitalize(string TEXT)
RETURNS TEXT
RETURN CONCAT(UPPER(LEFT(string,1)), LOWER(RIGHT(string, LENGTH(string) - 1)));
When I try to add variables using the DECLARE and SET keywords, it no longer works.
CREATE FUNCTION capitalize(string TEXT)
RETURNS TEXT
DECLARE first_letter TEXT;
DECLARE last_letters TEXT;
SET first_letter = UPPER(LEFT(string,1));
SET last_letters = LOWER(RIGHT(string, LENGTH(string) - 1));
RETURN CONCAT(first_letter, last_letters);
I get this error message
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4
I've fiddled around with it, removing semicolons, and double/triple checking parentheses. I've fiddled with BEGIN and END statements but nothing seems to work at all.
I have searched extensively on this topic but cannot figure out where the problem lies.
The body of a CREATE FUNCTION can consist of only a single statement, which is why the first version works and the second doesn't. Fortunately, that single statement can be a compound statement enclosed in a BEGIN ... END block.
You need to enclose the function body in a BEGIN ... END block to allow MySQL to see it as a single statement; you'll also perhaps need to precede and follow it with DELIMITER statements (depending on your client, as Mr. Berkowski points out):
DELIMITER //
CREATE FUNCTION capitalize(string TEXT)
RETURNS TEXT
BEGIN
DECLARE first_letter TEXT;
DECLARE last_letters TEXT;
SET first_letter = UPPER(LEFT(string,1));
SET last_letters = LOWER(RIGHT(string, LENGTH(string) - 1));
RETURN CONCAT(first_letter, last_letters);
END; //
DELIMITER ;
(Note especially the space between the last DELIMITER and the semicolon.)

MYSQL stored procedure

I am writing a stored procedure on MYSQL to check if there are recording matching some criteria and output values.
I am used to write in MSSQLSEVER
here is an excerpt of the procedure:
CREATE PROCEDURE prc1(
IN input VARCHAR(15),
OUT output INT
)
this_proc:
BEGIN
SET output = 0;
DECLARE inputCount INT DEFAULT 0;
SELECT COUNT(name) INTO inputCount FROM table WHERE table.name = input;
IF (inputCount> 0) THEN
SET output= 1;
LEAVE this_proc;
END IF;
END;
i am getting errors at each one of this lines:
SET output = 0;
DECLARE ...
IF ...
END IF;
END;
am i doing any syntax error or something?
Give this a shot. It gets past syntax errors, cleans up labels, points you toward fixing mytablename, wraps with delimiters, shows call.
drop procedure if exists prc1;
DELIMITER $$
CREATE PROCEDURE prc1(
IN input VARCHAR(15),
OUT output INT
)
-- this_proc:
BEGIN
DECLARE inputCount INT;
set input=0;
SET output = 0;
SELECT COUNT(name) INTO inputCount FROM mytablename WHERE name = input; -- fix mytablename
IF (inputCount> 0) THEN
SET output= 1;
-- LEAVE this_proc; -- not necessary, you are about to leave anyway !
END IF;
END;
$$ -- signify end of block
DELIMITER ; -- reset to default delimiter
Test it
call prc1('fred',#myVar);
Delimiters
Delimiters are important to wrap the block of the stored proc creation. The reason is so that mysql understands that the sequence of statements that follow are still part of the stored proc until it reaches the specified delimiter. In the case above, I made up one called $$ that is different from the default delimiter of a semi-colon that we are all used to. This way, when a semi-colon is encountered inside the stored proc during creation, the db engine will just consider it as one the many statements inside of it instead of terminating the stored proc creation. Without doing this delimiter wrapping, one can waste hours trying to create their first stored proc getting Error 1064 Syntax errors. At the end of the create block I merely have a line
$$
which tell mysql that that is the end of my creation block, and then the default delimiter of a semi-colon is set back with the call to
DELIMITER ;
Mysql manual page Using Delimiters with MySqlScript. Not a great manual page imo, but trust me on this one. Same issue when creating Triggers and Events.

Why does this function have a syntax error near DECLARE?

The code is:
DELIMITER $$
CREATE FUNCTION CHECK_AVABILITY(nama CHAR(30))
RETURNS INT(4)
DECLARE vreturn INT(4);
BEGIN
IF nama = 'ika' THEN
SET vreturn = 0;
ELSE
SET vreturn = 1;
END IF
RETURN vreturn;
END $$
The error message is:
ERROR 1064 (42000): You Have an error inyour sql syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE vreturn INT4); BEGIN'
Help is appreciated.
Move DECLARE vreturn INT(4) inside the BEGIN / END block. You probably also need a ; after the END IF.
Additionally, this looks like it is to be a DETERMINISTIC function. Add the DETERMINISTIC keyword before the BEGIN.
DELIMITER $$
CREATE FUNCTION CHECK_AVABILITY(nama CHAR(30))
RETURNS INT(4)
DETERMINISTIC
BEGIN
DECLARE vreturn INT(4);
IF nama = 'ika' THEN
SET vreturn = 0;
ELSE
SET vreturn = 1;
END IF;
RETURN vreturn;
END $$
Here's my findings on the subject:
This is a quote from a manual:
"You need a BEGIN/END block when you have more than one statement in the procedure. You use the block to enclose multiple statements.
But that's not all. The BEGIN/END block, also called a compound statement, is the place where you can define variables and flow of control."
In other words:
(These rules appear to apply to triggers and stored procedures in the same way, as it seems the same syntax is used in both.)
First, notice that a flow control group of keywords such as IF ... END IF or WHILE ... END WHILE is seen as a single statement as far as its termination with a semicolon is concerned, that is, it is terminated as a whole by a single semicolon at the end of it: IF ... END IF; WHILE ... END WHILE;.
Then, if the body of a trigger or stored procedure contains just one stament, and that statement is not a variable declaration nor a flow control group of keywords as above, that statement may not be terminated by a semicolon (;) and not enclosed by a BEGIN ... END block.
On the contrary, if the body of a trigger or stored procedure contains more than one stament, and particularly if it contains variable declarations and/or flow control groups of keywords, then it must be enclosed in a BEGIN ... END block.
Finally, the BEGIN ... END block itself must not be terminated by a semicolon.
Hope this helps.