Question

Any Ideas? I asked the question "Is it possible to have a default parameter for a mysql stored procedure?" today and the answer was a very strong "no this is not possible."

So my next question then is how do you as a php/mysql developer handle this problem? Do you pass null and in the SP have an IF block that sets the variable if its null? Do you pass a default value in PHP?

Thanks.

Was it helpful?

Solution

Here's one solution, using COALESCE() to set the value of a local variable in the stored proc:

DELIMITER !!

CREATE PROCEDURE dflt (IN param1 INT)
BEGIN
 DECLARE param1_dflt INT DEFAULT 456
 SET param1_dflt = COALESCE(param1, param1_dflt);

 SELECT param1_dflt;
END!!

DELIMITER ;

CALL dflt(123);
+-------------+
| param1_dflt |
+-------------+
|         123 | 
+-------------+


CALL dflt(NULL);
+-------------+
| param1_dflt |
+-------------+
|         456 | 
+-------------+

OTHER TIPS

Optional parameters are scheduled for MySQL 6.

Your easiest option is either to write a wrapper that adds the default values, or create procedures for each case.

I would consider your reasoning for using stored procedures. In the vast majority of cases they are of little benefit, as abstraction can be performed in the app layer and reduction of network traffic is usually the least of concerns. Of course, this depends on your app.

This should be handled by the database, not the calling script. If you can't define default parameters then pass NULL values and let the stored procedure do the defaulting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top