MySQL Function: Selecting and returning column - mysql

I have a table Processes, which consists of an ID (unsigned int, auto_increment) and Name (varchar, unique).
Selecting the following function with any input (whether in the table or not) always results in
ERROR 1172 (42000): Result consisted of more than one row
CREATE FUNCTION LookupOrInsertProcess(nametwo VARCHAR(255))
RETURNS INT UNSIGNED
BEGIN
DECLARE myid INT UNSIGNED;
SELECT ID INTO myid FROM Processes WHERE Name=nametwo;
RETURN myid;
END$$
However, selecting the below function always returns NULL:
CREATE FUNCTION LookupOrInsertProcess(nametwo VARCHAR(255))
RETURNS INT UNSIGNED
BEGIN
DECLARE myid INT UNSIGNED;
SELECT ID INTO myid FROM Processes WHERE Name=nametwo;
RETURN myid;
END$$
Furthermore, please note that the following does return the correct result (numbers 30 and 50 are arbitrary):
CREATE FUNCTION LookupOrInsertProcess(nametwo VARCHAR(255))
RETURNS INT UNSIGNED
BEGIN
DECLARE myid INT UNSIGNED;
SELECT ID INTO myid FROM Processes WHERE Name=nametwo;
IF myid IS NULL THEN
RETURN 30;
ELSE
RETURN 50;
END IF;
END$$
Any help is appreciated.
UPDATE: Edited to remove clash between table column and function param. I don't believe that's the issue.
UPDATE2: Please note that the following appears to work, both when the input param is or is not in the table. Why, without the coalesce(), does the function return NULL even for input params which are in the table?
CREATE FUNCTION LookupOrInsertProcess(nametwo VARCHAR(255))
RETURNS INT UNSIGNED
BEGIN
DECLARE myid INT UNSIGNED;
SELECT ID INTO myid FROM Processes WHERE Name=nametwo;
RETURN COALESCE(myid, 0);
END$$

Column names are not case-sensitive in MySql so you may find that where Name = name means 'give me every row'.
Try changing the input parameter to your procedure (and the corresponding condition in the query) to be srchName or something else different to name.

Try to rename input name to different name like inputName.
Update:
Another suggestion.
DECLARE myid INT UNSIGNED;
SET myid = (SELECT ID FROM Processes WHERE Name=nametwo);
RETURN myid;

Related

MySQL: Function not returning the correct integer

We have a question regarding a function returning the wrong integer-value in MySQL. We have checked that "booked_passengers" contains the right value, 0, and it works just fine when removing that variable, meaning just returning the integer 40. But as soon as we try to subtract "booked_passengers" from it, which still should end up returning 40, it does not work.
Including the code below.
Thanks in advance! :-)
CREATE FUNCTION calculateFreeSeats(flightnumber INT)
RETURNS INT
NOT DETERMINISTIC
BEGIN
DECLARE booked_passengers INT;
SELECT BOOKED_PASSENGERS INTO booked_passengers FROM FLIGHT WHERE (flightnumber = NR);
RETURN (40-booked_passengers);
END $$
When column name and local variable name interfere and there is no table alias then the variable is preferred. So your SELECT BOOKED_PASSENGERS ... selects variable value, not column value. Use
CREATE FUNCTION calculateFreeSeats(flightnumber INT)
RETURNS INT
READS SQL DATA
BEGIN
DECLARE booked_passengers INT;
SELECT FLIGHT.BOOKED_PASSENGERS INTO booked_passengers FROM FLIGHT WHERE (flightnumber = NR);
RETURN (40-booked_passengers);
END $$
From the other side the variable usage is obviously excess:
CREATE FUNCTION calculateFreeSeats(flightnumber INT)
RETURNS INT
READS SQL DATA
RETURN (SELECT 40 - BOOKED_PASSENGERS FROM FLIGHT WHERE flightnumber = NR LIMIT 1);

User defined function only returns NULL

I have this following MySQL code:
DELIMITER $$
CREATE FUNCTION durationInMinutes(id INT)
RETURNS INT DETERMINISTIC
BEGIN
DECLARE Minutes INT;
SET Minutes =
(SELECT TIME_TO_SEC(TIMEDIFF(timeDeparture, timeArrival)) FROM AirRoute
WHERE pk_id = id) / 60;
RETURN Minutes;
END$$
DELIMITER;
Basically, this function calculates the duration of a flight in minutes. The parameter is the id of the flight. For some reason though, this function always returns NULL. I even checked this:
SELECT (SELECT TIME_TO_SEC(TIMEDIFF(timeDeparture, timeArrival)) FROM AirRoute
WHERE pk_id = 925) / 60;
This does return the correct answer if I put id = 925, so there could be something wrong with the RETURN statement.
I suspect there is a column called id in the table. I always name parameters and local variables in a way to distinguish them from column names:
CREATE FUNCTION durationInMinutes (
in_id INT
)
RETURNS INT DETERMINISTIC
BEGIN
DECLARE out_Minutes INT;
SELECT out_Minutes := TIME_TO_SEC(TIMEDIFF(timeDeparture, timeArrival))
FROM AirRoute ar
WHERE ar.pk_id = in_id) / 60;
RETURN out_Minutes;
END$$
Ok, I solved it. This is my corrected code:
DELIMITER $$
CREATE FUNCTION durationInMinutes(id INT)
RETURNS INT DETERMINISTIC
BEGIN
RETURN (SELECT TIME_TO_SEC(TIMEDIFF(timeDeparture, timeArrival))
FROM AirRoute
WHERE pk_id = id / 60);
END$$
DELIMITER ;
Still, I really don't understand why it wasn't possible using a temp variable.

Why I received "null" even if the table contains a specific value for that column? [duplicate]

I have just started to create a stored function this is my first time so I am having a few problems. Currently I call the function using SELECT test(); (test is the function name for now). I want to send a number to the function (username ID) and have the username returned.
I have this working by using SELECT test(1); 1 is the ID of a user in the table. This seems to work as the username is returned, but if I type in any number the same username is returned also.
BEGIN
DECLARE new_username VARCHAR(90);
SELECT `username` INTO new_username FROM `users` WHERE `ID` = ID;
return new_username;
END
I have set the paramter as ID int .
Am I right in thinking that the keyword INTO will put the value of the username into the variable new_username ? If I run it without the INTO I get the error:
Not allowed to return a result set from a function
Have I made any obvious mistakes in this, I hope I havent done it totally wrong. Thanks for any advice :).
Edit : I just added a few more rows into my table , I now get the error:
Result consisted of more than one row
Full sql version:
CREATE DEFINER=`elliotts`#`%` FUNCTION `test`(ID int)
RETURNS varchar(32) CHARSET latin1
BEGIN
DECLARE new_username VARCHAR(32);
SELECT `username`
INTO new_username
FROM `users`
WHERE `ID` = ID;
return new_username;
END
Use:
DROP FUNCTION IF EXISTS `example`.`test` $$
CREATE FUNCTION `example`.`test` (param INT) RETURNS VARCHAR(32)
BEGIN
DECLARE new_username VARCHAR(32);
SELECT `username`
INTO new_username
FROM `users`
WHERE `ID` = param;
RETURN COALESCE(new_username, 'Username not found');
END $$
Mind that the VARCHAR length of the RETURN value matches the variable, which should match the column length you want to return.

Call a stored function in mysql,But get an error:Subquery returns more than 1 row

In mysql database,I have a table called 'usertest' which has some user information stored in it. And I create a UDF called 'getId' successfully. This is how it created:
create function getId(name varchar(255))
returns int
begin
declare id_found int;
set id_found=(select Id from usertest where Name=name);
return id_found;
end
It should be OK.However,when I call
select getId('mike');
mysql engine reports an error:
Subquery returns more than 1 row.
But in table usertest I have only one row where Name='mike'.That's wired.Someone can tell me why? Thank you in advance :)
Column names and variables are case-insensitive, so Name and name are the same thing. It's not comparing the Name column with the name variable, it's comparing the name variable with itself, so it's always true.
Use a different name for the function parameter.
create function getId(name_param varchar(255))
returns int
begin
declare id_found int;
set id_found=(select Id from usertest where Name=name_param);
return id_found;
end
or use a table name prefix.
create function getId(name varchar(255))
returns int
begin
declare id_found int;
set id_found=(select Id from usertest where usertest.Name=name);
return id_found;
end
See MySQL : When stored procedure parameter name is the same as table column name

MySQL stored function SELECT INTO unexpected results

I am trying to write a stored function in mysql 5.1 that returns the value 'AccountIDref' for a given room. If I only query the inner SELECT statement this works (returns the value for room). But invoking the function I get the response:
'#1172 - Result consisted of more than one row'
CREATE FUNCTION getAccountId (room INT) RETURNS INT
BEGIN
DECLARE refID INT DEFAULT NULL;
SELECT AccountIDref INTO refID FROM Allocation
WHERE Room = room;
RETURN refID;
END
What am I doing wrong here?
Field name and parameter name must be different -
CREATE FUNCTION getAccountId (room_param INT) RETURNS INT
BEGIN
DECLARE refID INT DEFAULT NULL;
SELECT AccountIDref INTO refID FROM Allocation
WHERE Room = room_param;
RETURN refID;
END
In your function you were getting all tables records.
What I am going to suggest isn't going to be much different from what you have, but I am skeptical about the where clause being in the next line and also let's use limit 1 to explicitly set the limit.
Try this :
CREATE FUNCTION getAccountId (room INT) RETURNS INT
BEGIN
DECLARE refID INT DEFAULT NULL;
SELECT AccountIDref INTO refID FROM Allocation WHERE Room = room LIMIT 1;
RETURN refID;
END