views:

170

answers:

3

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.

A: 

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.

ninesided
Thats only true of inserts
Matt
what's only true of inserts? I was expressing my opinion not a statement of fact...
ninesided
+1  A: 

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.

Matt
MySQL 6 doesn't mean the same thing as it used to; they changed all their future version numbers around. Can you edit your answer and include a link to cite where MySQL has publicized a plan to support this feature? I couldn't find anything related to it in bugs.mysql.com.
Bill Karwin
Oh - it was an old bug if I recall that got pipelined into a featured request for what was version 6. I know they are still working on stored procedures in version 6, so it may come out in a minor version release.
Matt
http://bugs.mysql.com/bug.php?id=15975
Matt
Verified and unassigned since end 2005 :(
Matt
Excellent! Thanks for the link!
Bill Karwin
Your welcome - good luck at OSCON btw. Unfortunately I have a stag weekend so i wont be coming :(
Matt
Thanks! It's okay, maybe you'll get there next year.
Bill Karwin
Thanks for the input Matt. Its good to know that at some point they will be doing this.
DJTripleThreat
They've acknowledged the feature request, but they haven't made any progress on it in four years. I think it's safe to assume they *won't* implement it, unless a community member contributes the code.
Bill Karwin
+3  A: 

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 | 
+-------------+
Bill Karwin
Wow! Good call! :D
Matt
+1 spot on Bill, this is what I was talking about
ninesided
Bill, this is a great example, thank you so much!
DJTripleThreat