在 MySQL 的存储过程中编写可选参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12652241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing optional parameters within stored procedures in MySQL?
提问by user1573747
I would like to create a stored procedure which updates either all fields in a table or just a few of them according to parameters passed to it.
我想创建一个存储过程,它根据传递给它的参数更新表中的所有字段或仅更新其中的几个字段。
How do I create a stored procedure that accepts optional parameters?
如何创建接受可选参数的存储过程?
回答by John Woo
Optional Parameters
are not yet supported on MySQL. I'm suggesting that you pass null
value in your parameter and inside your stored procedure has an IF
statement.
Optional Parameters
MySQL 尚不支持。我建议您null
在参数中传递值,并且在您的存储过程中有一个IF
语句。
DELIMITER $$
CREATE PROCEDURE procName
(IN param VARCHAR(25))
BEGIN
IF param IS NULL THEN
-- statements ;
ELSE commands
-- statements ;
END IF;
END$$
DELIMITER ;
回答by Antonio
An special case is when the parameter cant' be NULL, i.e. because is a key. I use a trick for these case: I set the parameter to -1:
一个特殊情况是当参数不能为 NULL 时,即因为是一个键。我对这些情况使用了一个技巧:我将参数设置为 -1:
CREATE PROCEDURE procCreate
(IN id_cosa INT(11))
BEGIN
IF id_cosa != -1 THEN
~~(your code here)~~
END IF
END