Assign In SELECT Command for MySQL Not working - mysql

I am trying to assign the #lastupd variable. as in below line:
select #lastupd := max(`last_edited_time`)
from flyspray_comments where task_id = taskID;
But mysql give me error:
ERROR 1064 (42000): 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 'BEGIN
set #lastupd = 0; select #lastupd := max(last_edited_time) from
flys' at line 2
The code:
delimiter $$
use flyspray $$
CREATE function last_upd_time(taskID INT)
BEGIN
set #lastupd = 0;
select #lastupd := max(`last_edited_time`) from flyspray_comments where task_id = taskID;
RETURN #lastupd;
END
$$
delimiter ;

Your immediate error has nothing to do with assignment. It is caused by the invalid definition of the function. You're missing mandatory RETURNS clause which indicates the return type of the function. See CREATE FUNCTION Syntax.
There is no need to use a variable in your case, less a user(session) variable. Just RETURN the result of the query.
And since you may use the only statement there is no need in a BEGIN ... END block and changing DELIMITER
That being said a streamlined and working version of your function may look like
CREATE FUNCTION last_upd_time(_task_id INT)
RETURNS DATETIME -- mandatory clause
RETURN -- just return the result of the query
(
SELECT MAX(last_edited_time)
FROM flyspray_comments
WHERE task_id = _task_id
); -- use default delimiter since it's a one-statement function
Here is SQLFiddle demo
Now, if you'd like to use a variable for some reason then
use a local instead of user(session) one.
assign a value with either SET or SELECT ... INTO syntax.
It may look like
DECLARE lastupd DATETIME DEFAULT NULL; -- or 0
SET lastupd =
(
SELECT MAX(last_edited_time)
FROM flyspray_comments
WHERE task_id = _task_id
);
or
DECLARE lastupd DATETIME DEFAULT NULL; -- 0
SELECT MAX(last_edited_time)
INTO lastupd
FROM flyspray_comments
WHERE task_id = _task_id;

Related

Stored function in MYSQL

If I have a TABLE named MyTable which has columns say C1(type date) and C2 (type character) I want to create a stored function that takes an input and the input should always belong to C1, and the output of the stored function should be the corresponding element in C2. I have tried to do it using the 'select' statement followed by 'where' clause inside the stored function but was not able to achieve it. Is there any other way to accomplish this task.
DELIMITER $$
CREATE FUNCTION `MyFunction`
(`Date` datetime)
RETURNS char(10)
BEGIN
DECLARE MyVariable char(10)
SELECT MyVariable = `C2`
FROM MyTable
WHERE `Date` = `C1`; RETURN MyVariable;
END$$
DELIMITER ;
But this keeps giving me ERROR CODE: 1064
At first glance, I see a syntax error:
...
BEGIN
DECLARE MyVariable char(10) <-- needs a semicolon here
SELECT MyVariable = `C2`
...
Every statement within the body of your routine must end with a semicolon. See examples of DECLARE in this manual page: https://dev.mysql.com/doc/refman/8.0/en/local-variable-scope.html
It should be like this:
...
BEGIN
DECLARE MyVariable char(10);
SELECT MyVariable = `C2`
...
Re your comment:
Error 1415 means "cannot return a result set". Your stored function is doing a SELECT without putting the result into your declared local variable using an INTO keyword.
You appear to be trying to set the value of MyVariable using = but that's just making a comparison. It doesn't assign anything to MyVariable.
Without using INTO to assign the variable, your SELECT statement is by default returning a result set. This is allowed in a stored procedure, but not in a stored function. A stored function must return a single scalar value, not a result set.
...
BEGIN
DECLARE MyVariable char(10);
SELECT `C2` INTO MyVariable
FROM MyTable
WHERE `Date` = `C1`;
RETURN MyVariable;
END
P.S.: I edited your question to replace the term "user-defined function" with "stored function". These are two different things in MySQL. You are writing a stored function.
In MySQL, they use the term user-defined function (UDF) for a function you implement in C/C++ code and compile into the MySQL server. It's less common for developers to write this type of extension.

MySQL - CREATE DEFINER syntax error

I am trying to update a stored function in our MySQL database. The update is to be released to multiple devices so I am doing it through an update.sql file.
Here is the function
DROP FUNCTION `STAFF_MPT`;
CREATE DEFINER=`jelena`#`%` FUNCTION `STAFF_MPT`(`par_stocktake_staff_id` INT) RETURNS DECIMAL(20,0) NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER BEGIN
DECLARE proc_total INT;
DECLARE proc_time INT;
SET proc_total = (SELECT SUM(quantity) FROM stocktake_scans WHERE stocktake_staff_id = par_stocktake_staff_id);
SET proc_time = (SELECT TIMESTAMPDIFF( SECOND , MIN( scan_date ) , MAX( scan_date ) ) AS area_time
FROM stocktake_scans
WHERE stocktake_staff_id = par_stocktake_staff_id
);
RETURN (proc_total/proc_time)*3600;
END
It was just reported to me by the test team that the report that uses this function did not generate properly. I tried to run the code in PMA SQL query window and got the following:
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 3
Can someone tell me what am I missing? According to this, line 3 is empty, so how could it possibly have a syntax error?
As of MySQL docs:
If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.
To redefine the mysql delimiter, use the delimiter command.
#juergen_d hinted in the comment: you have to define your procedure with a delimiter:
DROP FUNCTION `STAFF_MPT`;
delimiter ||
CREATE DEFINER=`jelena`#`%` FUNCTION `STAFF_MPT`(`par_stocktake_staff_id` INT) RETURNS DECIMAL(20,0) NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER BEGIN
DECLARE proc_total INT;
DECLARE proc_time INT;
SET proc_total = (SELECT SUM(quantity) FROM stocktake_scans WHERE stocktake_staff_id = par_stocktake_staff_id);
SET proc_time = (SELECT TIMESTAMPDIFF( SECOND , MIN( scan_date ) , MAX( scan_date ) ) AS area_time
FROM stocktake_scans
WHERE stocktake_staff_id = par_stocktake_staff_id
);
RETURN (proc_total/proc_time)*3600;
END
||
delimiter ;

Mysql error: Not allowed to return a result set from a function

I am trying to have a conditional change in a parameter for update statement.
I am getting the following error when I try the following function
/home/y/bin/mysql -u root < testpri.sql > out
ERROR 1415 (0A000) at line 4: Not allowed to return a result set from a function
Contents of testpri.sql are as follows:
use `zestdb`;
DROP FUNCTION IF EXISTS UPDATEPASSWD;
DELIMITER //
CREATE FUNCTION UPDATEPASSWD(n INT) RETURNS varchar(255) DETERMINISTIC
BEGIN
DECLARE mypasswd varchar(255);
IF (n = 1) THEN
SET mypasswd = '12ccc1e5c3c9203af7752f937fca4ea6263f07a5';
SELECT 'n is 1' AS ' ';
ELSE
SET mypasswd = '1a7bc371cc108075cf8115918547c3019bf97e5d';
SELECT 'n is 0' AS ' ';
END IF;>
SELECT CONCAT('mypasswd is ', mypasswd) AS ' ';
RETURN mypasswd;
END //
DELIMITER ;
CALL UPDATEPASSWD(0);
What am I missing?
I think it's actually your debugging SELECT calls.
From the docs:
Statements that return a result set can be used within a stored procedure but not within a stored function. This prohibition includes SELECT statements that do not have an INTO var_list clause...
I arrived in search of answers to the same question, and found another way to work around the issue, so that I can use the SELECT statement that is the heart and soul of the MySQL function that elicited the warning.
Consider the following snippet.
SET intNMatches = ( SELECT COUNT(*) ...
SET coerces the SELECT statement to return its one and only column, a row count, into intNMatches, a local variable cast to BIGINT. Since it contains trade secrets, I can't show the rest of the query. Suffice it to say that the query installs without causing the MySQL engine to issue a warning.

mySQL If statement

I am trying to make this If Statement work, but I can't seem to make it do what I want. If I do a select #result, It'll give me the value 0, then why doesn't the IF statement work?
SET #message = '((sometihng here))';
select LEFT(#message, 1) into #firstChar;
select STRCMP(#firstChar,'(') into #result;
IF (#result = 0) THEN
SET #message = 'true';
//more selects and cals here;
END IF;
select #message;
I should get true, but I don't it shows me an error:
SQL query: IF( #result =0 ) THEN SET #message = 'true';
MySQL said:
1064 - 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 'IF (#result = 0) THEN SET #message = 'true'' at line 1
try use function http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if
SELECT IF(#result = 0, 'true', '((something here))') AS message
As Max Mara pointed out, that's a good work aroud. The reason the IF wasn't working is not because the syntax is incorrect, but because flow control functions like IF ... THEN are only valid inside of stored procedures or functions, All this thanks to #TehShrike
The IF .. THEN .. ELSE syntax in MySQL is only available for procedural code (stored precudures, functions, triggers..), but not for SELECT statements.
IF ELSE USED IN STORED PROCEDURE EXAMPLE BELOW
DELIMITER //
CREATE PROCEDURE NAME(IN Number INT)
BEGIN
IF roll= 1
THEN SELECT * FROM table1 WHERE id = roll;
ELSE
SELECT * FROM table2 WHERE id = 2;
END IF;
END //
DELIMITER ;

Mysql function returning a value from a query

i want to create a function which calculates a value using a query and I am having a problem returning the value:
Shortened, my query is:
CREATE FUNCTION func01(value1 INT , monto DECIMAL (10,2)) RETURNS DECIMAL(10,2)
BEGIN
SET #var_name = 0;
select #var_name=if(value1 = 1,monto * table.divisa_dolar,table.monto *divisa_euro) from table where data_init = 1;
return #var_nam;
END
I get a SQL syntax error.
SQL Error (1064): You have an error in your SQL syntax;
Assuming these are all generic names (table will not be a good table name), the problem is you can't use == for comparison. You are also missing some key syntax (DECLARE, SELECT INTO, etc.).
Change to this:
CREATE FUNCTION func01(value1 INT , monto DECIMAL (10,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
DECLARE var_name DECIMAL(10,2);
SET var_name = 0;
SELECT if(value1 = 1,monto *divisa_dolar,monto *divisa_euro) INTO var_name
FROM table
WHERE data_init = 1;
RETURN var_name;
END
MySQL Comparison Functions and Operators
Related Question: Single Equals in MYSQL
Function Help: http://www.databasejournal.com/features/mysql/article.php/3569846/MySQL-Stored-Functions.htm