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 中创建一个带有可选参数的函数
基础教程推荐
- 在 SQL 中连接多个表 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
