在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:02:03  来源:igfitidea点击:

Writing optional parameters within stored procedures in MySQL?

mysqlstored-procedures

提问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 Parametersare not yet supported on MySQL. I'm suggesting that you pass nullvalue in your parameter and inside your stored procedure has an IFstatement.

Optional ParametersMySQL 尚不支持。我建议您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