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> ..
Related
Deal all,
I have a JSON data as follows:
set #injsondata = '{
"action": "SaveEventByMinutes",
"eventbyminutes": [{"matchid":10001,"minute":"1","halftime":"1","value":"A","userid":1,"createddate":"2021-09-25"},
{"matchid":10001,"minute":"2","halftime":"1","value":"X","userid":1,"createddate":"2021-09-25"}]}';
Now I want to change the matchid value to 10002 using select statement in MySQL.
What I have tried
1. select JSON_merge_patch(#injsondata,'{"eventbyminutes[*]":{"matchid": 10002}}');
2. SELECT JSON_replace(#injsondata, '{"eventbyminutes":{"matchid":2}}');
But nothing is working
Is there any other option to do this?
or do I have to create a function or procedure like
DELIMITER $$
CREATE DEFINER=`root`#`localhost` FUNCTION `func_modify_json`(injsondata json) RETURNS json
DETERMINISTIC
begin
declare len int default json_length(injsondata);
declare i int default 0;
declare outjsondata json;
while i < len do
# Replace the report4 property of the i'th element with an empty list
set outjsondata = JSON_replace(injsondata,'$[0].eventbyminutes[i].matchid',10002);
set i = i + 1;
end while;
return outjsondata;
end$$
DELIMITER ;
Something like above?
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
I have a field text, In it there is information about such
sch hcbhsc hscbshcbc xxxxxxxx sgxfag jdhajdh;
dchbdbc bdcbdh bchdbd xx/xx-xxxx/xx svdhs sbjbsc
bdchbdc jncjdnc jbcjb xx/xx-xxxxx/xx gcvsgc jcbjsb
dchjbd bhjcbdcb bdcbcd xx-xxxx/xx shchscv hscbhsc
dhcbhd jdcbjdb jdcnjdcn xx-xxxxx/xx shcvsch jbscjc
Place x is only a digit, I need to write select and only those numbers are taken
Use SUBSTRING and PATINDEX string functions IN SQL server :
SELECT SUBSTRING(Your_FieldName, PATINDEX('%[0-9]%', Your_FieldName),
LEN(Your_FieldName))
For MYSQL refer below URL :
Query to get only numbers from a string
string
There is no formal PATINDEX() function in MySQL that achieves both the regex pattern lookup with returned character index, define User-Defined function that loops through each character in the length of a string and checks a REGEXP pattern on the character. Once created, use such a function in-line of a query.
DROP FUNCTION IF EXISTS PatIndex;
DELIMITER $$
CREATE FUNCTION PatIndex(pattern VARCHAR(255), tblString VARCHAR(255)) RETURNS INTEGER
DETERMINISTIC
BEGIN
DECLARE i INTEGER;
SET i = 1;
myloop: WHILE (i <= LENGTH(tblString)) DO
IF SUBSTRING(tblString, i, 1) REGEXP pattern THEN
RETURN(i);
LEAVE myloop;
END IF;
SET i = i + 1;
END WHILE;
RETURN(0);
END
Here is a MySQL function (routine) that will do just that. It is an improved version from the solution given here: how-to-get-only-digits-from-string-in-mysql
This improved version can handle much larger numbers. The old solution was limited by the INTEGER value, so if you had phone numbers for example (or string containing many digits), it would fail with out of range for column.
DELIMITER $$
CREATE FUNCTION ExtractNumber (in_string VARCHAR(50))
RETURNS varchar(50)
NO SQL
BEGIN
DECLARE ctrNumber VARCHAR(50);
DECLARE finNumber VARCHAR(50) DEFAULT '';
DECLARE sChar VARCHAR(1);
DECLARE inti VARCHAR(50) DEFAULT 1;
IF LENGTH(in_string) > 0 THEN
WHILE(inti <= LENGTH(in_string)) DO
SET sChar = SUBSTRING(in_string, inti, 1);
SET ctrNumber = FIND_IN_SET(sChar, '0,1,2,3,4,5,6,7,8,9');
IF ctrNumber > 0 THEN
SET finNumber = CONCAT(finNumber, sChar);
END IF;
SET inti = inti + 1;
END WHILE;
RETURN CAST(finNumber AS UNSIGNED);
ELSE
RETURN 0;
END IF;
END$$
DELIMITER ;
Now you can do this:
SELECT ExtractNumber(my_field)
FROM my_table;
I am tring to perform a BITOR on a argument that i am passing into a function. so i wrote the below code. Statement 'SET result = arg1 | arg2 ' isnt working. I tried few ways, however i wasnt able to achieve the right result. What do i need to change ?
DELIMITER $$
CREATE FUNCTION BIT_OR(arg1 varchar(255),arg2 varchar(255)) RETURNS varchar(255)
BEGIN
DECLARE result varchar(255);
BEGIN
SET result = arg1 | arg2;
END;
RETURN result;
END $$
DELIMITER ;
select bitwise_OR(00011101,00001111); -- 12127 ( i am expecting 00011111 or 31 (decimal equivalent))
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 ;