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;
Related
Here's what I've tried. My host is returning an error, "Sorry an unexpected error happened!" .
I want it to return true if there is at least 1 record with combination pdriver_id, ptruck_number, and pdate.
DELIMITER %%
CREATE FUNCTION DriverActiveInTruckByDate(
pdriver_id INT,
ptruck_number INT,
pdate DATETIME
)
RETURNS boolean
DETERMINISTIC
BEGIN
DECLARE inDB INT DEFAULT 0;
SET inDB =
SELECT IF(COUNT(*) >= 1,1,0)
FROM
truck_timeline tl
WHERE 1=1
AND tl.driver_id = pdriver_id
AND tl.truck_number = ptruck_number
AND ((pdate BETWEEN tl.begin_date AND tl.end_date) OR (pdate >= tl.begin_date AND tl.end_date IS NULL))
END
%%
DELIMITER ;
Several fixes are needed:
The function is not DETERMINISTIC. This means the result will always be the same given the same inputs. In your case, the result may be different depending on the data in your truck_timeline table. So I would suggest using READS SQL DATA.
If you use SET variable = SELECT... you must put the SELECT in a subquery:
SET inDB = (SELECT ...);
The current manual recommends using SELECT ... INTO variable instead of SET. See https://dev.mysql.com/doc/refman/8.0/en/select-into.html
The INTO position at the end of the statement is supported as of MySQL 8.0.20, and is the preferred position.
SELECT ... INTO inDB;
The function you show doesn't have a RETURN statement. See https://dev.mysql.com/doc/refman/8.0/en/return.html
There must be at least one RETURN statement in a stored function.
Your Full Code could be like this:
DELIMITER %%
CREATE FUNCTION DriverActiveInTruckByDate(
pdriver_id INT,
ptruck_number INT,
pdate DATETIME
)
RETURNS boolean
DETERMINISTIC
BEGIN
DECLARE inDB INT DEFAULT 0;
SET inDB =
(SELECT IF(COUNT(*) >= 1,1,0)
FROM
truck_timeline tl
WHERE 1=1
AND tl.driver_id = pdriver_id
AND tl.truck_number = ptruck_number
AND ((pdate BETWEEN tl.begin_date AND tl.end_date) OR (pdate >= tl.begin_date AND tl.end_date IS NULL))
);
END %%
DELIMITER ;
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.
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.
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 ;
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