mysql custom function syntax - mysql

hi this is my first post here. A novice web development student.
so this first function checks to see if a string contains 'cabo verde' or 'cambodia' or 'cameroon' if yes then just return the original string. otherwise if the string begins with CA regardless of upper or lower case then it returns the string 'CAN'. I think i am getting some syntax wrong as this is my first time creating custom functions in mysql.
DELIMITER $$
create function cleanstr(
string1 VARCHAR(60)
)
returns VARCHAR(60)
DETERMINISTIC
BEGIN
IF(LOWER(string1) = 'cabo verde' OR LOWER(string1) = 'cambodia' OR LOWER(string1) = 'cameroon')
THEN return string1;
ELSE IF (REGEXP_LIKE(string1,'^ca','i') = 1)
THEN return 'CAN';
END IF;
END; $$
DELIMITER ;
this function takes 3 integer values. if first two are null then it returns both those variables equal to 0. If the 3rd variable is NULL then it throws a 45000 error.
DELIMITER $$
create function ints(
num1 int, num2 int, num3 int
)
returns int
DETERMINISTIC
BEGIN
IF(ISNULL(num1) = 1 AND ISNULL(num2) = 1)
THEN
return num1 = 0 AND num2 = 0;
ELSE IF (ISNULL(num3) = 1)
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Third value is NULL';
END IF;
END; $$
DELIMITER ;
I can't figure out what exactly i am missing in these functions. Hope it is something small. Thanks

Related

using if else in mysql user defined function

This is my query that basically takes two numbers that adds them and multiplies the sum by 10
DELIMITER $$
CREATE FUNCTION tot(a int(4),b INT(4)) RETURNS INT(4)
BEGIN
RETURN ROUND((a+b)*10/9);
END $$
DELIMITER ;
everything is working fine , but I was wondering if there was a way I could add an IF ELSE
that checks if any of of the values entered is null and if so the null value is assigned a value of zero
I've tried this but I'm getting an error
DELIMITER $$
CREATE FUNCTION tot(a int(4),b INT(4)) RETURNS INT(4)
BEGIN
IF (a = "") then
a=0;
ELSE IF (b = "")
b=0;
ELSE
END IF;
RETURN ROUND((a+b)*10/9);
END $$
DELIMITER ;
I was wondering if there was a way I could add an IF ELSE that checks if any of of the values entered is null and if so the null value is assigned a value of zero
You can just use coalesce() to assign a default to null parameters:
DELIMITER $$
CREATE FUNCTION tot(a int(4),b INT(4)) RETURNS INT(4)
BEGIN
RETURN ROUND((COALESCE(a, 0) + COALESCE(b, 0)) * 10 / 9);
END $$
DELIMITER ;

Creating a function in mysql with if exists

I am trying to create a function in MySQL like so, bu tI am getting a syntax error at the if exists line:
I think I am doing something slightly off as a result of translation from MS SQL server.
CREATE FUNCTION MyFunction(input_field INTEGER)
RETURNS VARCHAR(5)
BEGIN
IF EXISTS (SELECT * FROM Teaches WHERE courseid = input_field)
RETURN 'True'
RETURN 'false'
END;
**UPDATE
The solution I found based on the answer from #SK Jajoriya
DELIMITER $$
CREATE FUNCTION MyFunction2(input_field INTEGER)
RETURNS VARCHAR(5)
BEGIN
IF EXISTS (SELECT * FROM Teaches WHERE courseid = input_field) THEN
RETURN 'True';
ELSE
RETURN 'False';
END IF;
END $$
CREATE FUNCTION MyFunction(input_field INTEGER)
RETURNS VARCHAR(5)
BEGIN
IF EXISTS (SELECT * FROM Teaches WHERE courseid = input_field) THEN
RETURN 'True'
ELSE
RETURN 'false'
END IF;
END;
In your case, the if statement not closed
IF should be finished with END IF
https://dev.mysql.com/doc/refman/5.7/en/if.html
But in your case it's better to
CREATE FUNCTION MyFunction(input_field INTEGER)
RETURNS VARCHAR(5)
BEGIN
DECLARE res VARCHAR(5);
SET res = IF(EXISTS (SELECT 1 FROM Teaches WHERE courseid = input_field LIMIT 1),'true','false');
RETURN res;
END;
here is a fiddle
https://www.db-fiddle.com/f/uFkXXDpqVjn6AjYkXx3EYM/0

MySQL Function getting Syntax Error

I am trying to create the below function in MySQL but getting syntax error.
I am not able to find the solution, would be grateful for some help
CREATE FUNCTION `test`.`pro`(depart_id int) RETURNS varchar
BEGIN
DECLARE title varchar;
if depart_id = 1 then
set title='IT Department';
else if depart_id = 2 then
set title='HR Department';
else
set title='Admin';
end if;
return title;
END$$
DELIMITER ;
You have several syntax errors in your script:
varchar must have a length
You should define DELIMITER $$ first
It's not else if, but elseif
Try this;)
DELIMITER $$
CREATE FUNCTION `test`.`pro`(depart_id int) RETURNS varchar(10)
BEGIN
DECLARE title varchar(10);
if depart_id = 1 then
set title='IT Department';
elseif depart_id = 2 then
set title='HR Department';
else
set title='Admin';
end if;
return title;
END $$
DELIMITER ;

MySQL syntax (function) is error

CREATE FUNCTION FC_IDKRITERIA()
RETURNS CHAR(3)
AS
BEGIN
DECLARE #MAX INT , #KODEBARU CHAR(3)
SELECT #MAX = MAX (RIGHT(IDKRITERIA,2)) FROM KRITERIA
IF #MAX IS NULL
SET #MAX = 0
SET #KODEBARU = 'K' + RIGHT('0'+CONVERT(VARCHAR(3),#MAX+ 1 ) ,2)
RETURN #KODEBARU
END
Every statement in a procedure must end with ;. To keep this from ending the function definition, use the DELIMITER command to change the command delimiter to something else.
And when doing a variable assignment in a SELECT clause, you have to use :=.
There's no AS at the beginning of a function definition.
You don't declare variables that begin with #.
You need THEN and END IF in an IF statement.
To concatenate strings, use CONCAT(), not +.
You have the arguments to CONVERT() in the wrong order, and VARCHAR(3) is not a valid type argument, it should be CHAR(3).
In a function, you can't use a SELECT statement at the top-level, because that means to return the result set, and functions can only return single values. So you have to assign #MAX from a (SELECT ...) expression.
DELIMITER $$
CREATE FUNCTION FC_IDKRITERIA() RETURNS CHAR(3)
BEGIN
SET #MAX = (SELECT MAX (RIGHT(IDKRITERIA,2)) FROM KRITERIA);
IF #MAX IS NULL
THEN SET #MAX = 0;
END IF;
SET #KODEBARU = CONCAT('K', RIGHT('0'+CONVERT(#MAX+ 1, CHAR(3)) ,2));
RETURN #KODEBARU;
END;
$$
DELIMITER ;

Create a function with optional arguments in MySQL

I want to create a function with optional arguments in MySQL. For instance, I want to create function that calculates the average of its arguments. I create a function of five arguments, but when user passes just two arguments to the function then it should still run and return the average of the two arguments.
You cannot set optional parameters in MySQL stored procedures.
You can however set optional parameters in a MySQL UDF.
You do know that MySQL has an AVG aggregate function?
Workaround
If you can face the ugliness of this workaround here's samplecode that uses a comma separated string with values as input and returns the average.
DELIMITER $$
CREATE FUNCTION MyAvg(valuestr varchar) RETURNS float
BEGIN
DECLARE output float;
DECLARE arg_count integer;
DECLARE str_length integer;
DECLARE arg float;
DECLARE i integer;
SET output = NULL;
SET i = LENGTH(valuestr);
IF i > 0 THEN BEGIN
SET arg_count = 1;
WHILE i > 0 DO BEGIN
IF MID(valuestr, i, 1)
SET i = i - 1;
END; END WHILE;
/* calculate average */
SET output = 0;
SET i = arg_count;
WHILE i > 0 DO BEGIN
SET arg = SUBSTRING_INDEX(
SUBSTRING_INDEX(valuestr, ',' , i)
, ',', -1 );
SET output = output + arg;
SET i = i - 1;
END; END WHILE;
SET output = output / arg_count;
END; END IF;
RETURN output;
END $$
DELIMITER ;
Use concat_ws to feed the function.
SELECT MyAvg(CONCAT_WS(',',100,200,300,500)) AS test;
You can also write an UDF in C(++) or Delphi/Lazarus
While far from an ideal solution, here's how I solved optional parameters for a concat function I needed:
delimiter ||
create function safeConcat2(arg1 longtext, arg2 varchar(1023))
returns longtext
return safeConcat3(arg1, arg2, '');
||
create function safeConcat3(arg1 longtext, arg2 varchar(1023), arg3 varchar(1023))
returns longtext
return safeConcat4(arg1, arg2, arg3, '');
||
create function safeConcat4(arg1 longtext, arg2 varchar(1023), arg3 varchar(1023), arg4 varchar(1023))
returns longtext
begin
declare result longText;
set result = concat(arg1, arg2, arg3, arg4);
if( result is null) then
set result=arg1;
end if;
return result;
end
||
Note: This means you have to call the method that corresponds to the number of args.
Another approach is to pass only one 'super' parameter which is string with commas in it separating the real parameters. The mysql procedure can then parse the 'super' parameter into the separate real parameters.
Example:
create procedure procWithOneSuperParam(param1 varchar(500))
declare param2 varchar(100);
begin
if LOCATE(',',param1) > 0 then
.. param2=<extract the string after the ',' from param1> ..