MySql Function Creation Error - mysql

I write a function like the following. the purpose of this function is to return the place of a student by some specific exam in a branch.
DELIMITER $$
CREATE FUNCTION `getMerit`( branch VARCHAR(50), totalMark DECIMAL(19,2), comaSeparetedExamIds VARCHAR(200) ) RETURNS INT(11)
BEGIN
SET #comaSeparetedExamIds=comaSeparetedExamIds;
SET #branch =branch;
SET #marks=totalMark;
SELECT #place=COUNT(*)+1
FROM (
SELECT SUM(m.marks) marks
FROM marksheet m, studentinfo s
WHERE exam_id IN (#comaSeparetedExamIds)
AND m.student_roll=s.roll_no
AND s.branch LIKE CONCAT(#branch,'%')
GROUP BY m.student_roll
) AS a
WHERE a.marks>#totalMark;
RETURN #place;
END$$
DELIMITER ;
But It shows me an error. the Error is
Query : CREATE FUNCTION getMerit( branch varchar(50), totalMark
DECIMAL(19,2), comaSeparetedExamIds varchar(200) ) RETURNS int(11)
BEG... Error Code : 1415 Not allowed to return a result set from a
function
What mistake I made here, Can anyone please help me?

You can't name input variables with #. # is used for user variables, ie connection local variables that don't needs to be declared.
Also you can't have selects in functions.
Procedures can return result sets but return values.
Functions can return values but not result sets.
They also differs in how you use them.
select function_name(1) from dual;
select id, name, funcation_name(id, name) from anyTable;
call procedure_name(1);
And when assigning variables inside selects you need to do := and not =. In your code you are actually selecting true or false and not the count.
This should work.
DELIMITER $$
CREATE FUNCTION `getMerit`( branch VARCHAR(50), totalMark DECIMAL(19,2), comaSeparetedExamIds VARCHAR(200) ) RETURNS INT(11)
BEGIN
SET #comaSeparetedExamIds=comaSeparetedExamIds;
SET #branch =branch;
SET #marks=totalMark;
SELECT COUNT(*)+1 INTO #place
FROM (
SELECT SUM(m.marks) marks
FROM marksheet m, studentinfo s
WHERE exam_id IN (#comaSeparetedExamIds)
AND m.student_roll=s.roll_no
AND s.branch LIKE CONCAT(#branch,'%')
GROUP BY m.student_roll
) AS a
WHERE a.marks>#totalMark;
RETURN #place;
END$$
DELIMITER ;

Related

Ask how to pass in a parameter that returns the value of 2 columns in a table in the mysql function

DELIMITER $$
CREATE DEFINER=`root`#`localhost` FUNCTION `sumwhere`(`mus_level` INT) RETURNS int(11)
READS SQL DATA
begin
declare tong int;
select sum(us_id) into tong
from members
where us_level = mus_level
group by us_level;
return tong;
end$$
DELIMITER ;
CREATE FUNCTION FUNC_1_MANV
(
#MANV CHAR(10)
)
RETURNS #TABLE TABLE(HOTEN NVARCHAR(30), CHUCVU NVARCHAR(30))
AS
BEGIN
INSERT INTO #TABLE
SELECT TENNV , CHUCVU
FROM NHANVIEN
WHERE MANV=#MANV
RETURN
END
GO
--THỰC THI
SELECT * FROM dbo.FUNC_1_MANV('NV001')
GO
enter image description here
I want to do the same as below code func "FUNC_1_MANV" but using MySQL.
I want to display one more column of mine, like count(us_id) , or the value of a column (us_id) when I have where run on create function MySQL how. I see MySQL only return 1 parameter.

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.

Mysql variable value is null

CREATE PROCEDURE `checkAdminAccess`
(
IN accountID INT
)
BEGIN
DECLARE staffID INT;
#DECLARE num INT;
SELECT StaffID INTO staffID
FROM staff
WHERE AccountID = accountID
AND IsAdmin = 1;
SELECT staffID;
IF (staffID IS NULL) THEN
CALL raise(1356, 'Admin access required.');
END IF;
END;
For any input I get the staffID as NULL.
For example:
call checkAdminAccess(3); #returns null
call checkAdminAccess(6); #returns null
And my data is below:
INSERT INTO `staff` (`StaffID`,`AccountID`,`RoleID`,`ManagerID`,`IsAdmin`) VALUES (1,3,1,1,0);
INSERT INTO `staff` (`StaffID`,`AccountID`,`RoleID`,`ManagerID`,`IsAdmin`) VALUES (2,6,2,1,1);
Can someone tell me how to do select a value into a variable in Mysql?
The problem is that you check the return value of a procedure, which must be null, since a procedure does not return any value. It maximum returns a resultset.
Possible solutions:
Change the procedure to function, that returns the staffid.
Add an out parameter to the procedure and use that to retrieve the staffid. The above link also describes how to do this.

MySQL Stored Procedure returns 0 in parameters from a SELECT

I created a Stored Procedure in MySQL to return some parameters from a SELECT, but doesn't work.
ever returns 0 in userID and otherID.
Someone can help me?
Thanks
DROP PROCEDURE IF EXISTS sp_XPTO;
DELIMITER ;;
CREATE PROCEDURE sp_XPTO(
OUT userID INT UNSIGNED,
OUT otherID INT UNSIGNED,
IN bookID INT UNSIGNED
)
BEGIN
SELECT userID=E.userID, otherID=E.otherID
FROM Exp as E
WHERE E.bookID = bookID;
END ;;
DELIMITER ;
UPDATED:
Sorry,
After I read a lot, I concluded that the error is in how I call the stored procedure, and Ravinder is correct.
Thanks
I am not sure if your intention is to check the existence of a value in database.
Because, your select statement is doing a comparison but not assignment.
SELECT userID=E.userID, otherID=E.otherID
With the above statement, you may be thinking that value of E.userID is assigned to the OUT parameter userID. But the syntax you used is wrong.
In the above statement, both of the expressions return a boolean. As userID value did not match with E.userID the comparison resulted a false and you saw a 0. And it was the same for the otherID variable.
To assign values to variables you have to use INTO instructional operator.
Example:
SELECT E.userID, E.otherID
INTO userID, otherID
Change your stored procedure as below:
DROP PROCEDURE IF EXISTS sp_XPTO;
DELIMITER //
CREATE PROCEDURE sp_XPTO(
OUT userID INT UNSIGNED,
OUT otherID INT UNSIGNED,
IN bookID INT UNSIGNED
)
BEGIN
SELECT E.userID, E.otherID
INTO userID, otherID
FROM Exp as E
WHERE E.bookID = bookID; -- <- there was a ')'. removed.
END;
//
DELIMITER ;
Call the procedure with desired parameters and read the out parameters.
call sp_XPTO( #userID, #otherID, 234 ); -- where book id is 234
select #userID, #otherID;

MySql Function Is not giving proper result

I have created mysql function as below
DELIMITER $$
DROP FUNCTION IF EXISTS `GetProductIDFunc`$$
CREATE FUNCTION `GetProductIDFunc`( countryid INT (10) )
RETURNS VARCHAR(200)
BEGIN
declare out_id VARCHAR;
select country_percentage INTO out_id from country_markup where estatus = '1' AND `country_id` REGEXP '[[:<:]]countryid [[:>:]]' limit 1;
RETURN out_id;
END$$
DELIMITER ;
And I have called this function like as below
SELECT GetProductIDFunc( 223 )
but it gave me NULL value instead of 7 which is my expected result value.
Check sample data here for above result [link] http://sqlfiddle.com/#!2/6aa92
Note: IF i replace '[[:<:]]countryid [[:>:]]' with static value like '[[:<:]]223 [[:>:]]' than function return desire result.
Help will be appreciated.
MySQL doesn't substitute values of variables inside of strings. You can form the regular expression using concat, for example:
select country_percentage INTO out_id from country_markup
where estatus = '1' AND `country_id` REGEXP concat('[[:<:]]',countryid,'[[:>:]]')
limit 1;