問題描述
我正在嘗試創建一個 MySQL 函數 IS_IN_ENUM('value', 'val1', 'val2', 'val3')
如果 'value' 在 ('val1','val2', 'val3').我知道我可以做 SELECT 'value' IN ('val1', 'val2', 'val3')
但這不太有趣,因為我只想學習如何創建這樣的函數.
I am trying to create a MySQL function IS_IN_ENUM('value', 'val1', 'val2', 'val3')
which return true if 'value' is in ('val1', 'val2', 'val3'). I know I can do SELECT 'value' IN ('val1', 'val2', 'val3')
but that's less intersting because I just want to learn how to create such functions.
我舉個例子,考慮下面的ADD
函數:
I give you an example, consider the following ADD
function :
CREATE FUNCTION my_add (
a DOUBLE,
b DOUBLE
)
RETURNS DOUBLE
BEGIN
IF a IS NULL THEN
SET a = 0;
END IF;
IF b IS NULL THEN
SET b = 0;
END IF;
RETURN (a + b);
END;
如果我執行 SELECT my_add(1, 1)
,我得到 2(哇!).
If I do SELECT my_add(1, 1)
, I get 2 (wow!).
如何改進此功能以使其能夠調用:
How can I improve this function to be able to call :
SELECT my_add(1, 1); -- 2
SELECT my_add(1, 1, 1); -- 3
SELECT my_add(1, 1, 1, 1); -- 4
SELECT my_add(1, 1, 1, 1, 1, 1, .....); -- n
推薦答案
您展示的函數示例是一個存儲函數,而不是 UDF.正如@Enzino 回答的那樣,MySQL 中的存儲函數不支持可變數量的參數.
The function example you show is a Stored Function, not a UDF. Stored Functions in MySQL don't support a variable number of arguments, as @Enzino answered.
MySQL UDF 是用 C 或 C++ 編寫的,編譯成動態目標??文件,然后通過 CREATE FUNCTION
的不同語法.
MySQL UDFs are written in C or C++, compiled into dynamic object files, and then linked with the MySQL server with a different syntax of CREATE FUNCTION
.
見http://dev.mysql.com/doc/refman/5.5/en/adding-udf.html 了解編寫 UDF 的詳細信息.但我不知道你是否想開始編寫 C/C++ 代碼來做到這一點.
See http://dev.mysql.com/doc/refman/5.5/en/adding-udf.html for details of writing UDFs. But I don't know if you want to get into writing C/C++ code to do this.
MySQL UDF 支持可變數量的參數.事實上,所有 UDF 都隱式地接受任意數量的參數,作為程序員,由您來確定給定參數的數量和數據類型是否對您的函數有效.
MySQL UDFs do support variable number of arguments. In fact, all UDFs implicitly accept any number of arguments, and it's up to you as the programmer to determine if the number and datatypes of the arguments given are valid for your function.
處理 UDF 中的函數參數記錄在 http://dev.mysql.com/doc/refman/5.5/en/udf-arguments.html
Processing function arguments in UDFs is documented in http://dev.mysql.com/doc/refman/5.5/en/udf-arguments.html
這篇關于創建一個帶有動態參數數量的 MySQL 存儲函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!