Create a function with optional arguments in MySQL(在 MySQL 中创建一个带有可选参数的函数)
问题描述
我想在 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.
推荐答案
您不能在 MySQL 存储过程中设置可选参数.
但是,您可以在 MySQL UDF 中设置可选参数.
You cannot set optional parameters in MySQL stored procedures.
You can however set optional parameters in a MySQL UDF.
你知道 MySQL 有一个 AVG 聚合函数?
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 ;
使用 concat_ws 提供函数.
Use concat_ws to feed the function.
SELECT MyAvg(CONCAT_WS(',',100,200,300,500)) AS test;
您还可以编写 UDFC(++) 或 Delphi/Lazarus
这篇关于在 MySQL 中创建一个带有可选参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 MySQL 中创建一个带有可选参数的函数


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01