Quantcast
Channel: Is it possible to have a default parameter for a mysql stored procedure? - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by Ross Smith II for Is it possible to have a default parameter for a mysql stored procedure?

$
0
0

Unfortunately, MySQL doesn't support DEFAULT parameter values, so:

CREATE PROCEDURE `blah`(  myDefaultParam int DEFAULT 0)BEGIN  -- Do something hereEND

returns the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manualthat corresponds to your MySQL server version for the right syntax to use near 'DEFAULT 0) BEGIN END' at line 3

To work around this limitation, simply create additional procedures that assign default values to the original procedure:

DELIMITER //DROP PROCEDURE IF EXISTS blah//DROP PROCEDURE IF EXISTS blah2//DROP PROCEDURE IF EXISTS blah1//DROP PROCEDURE IF EXISTS blah0//CREATE PROCEDURE blah(param1 INT UNSIGNED, param2 INT UNSIGNED)BEGIN    SELECT param1, param2;END;//CREATE PROCEDURE blah2(param1 INT UNSIGNED, param2 INT UNSIGNED)BEGIN    CALL blah(param1, param2);END;//CREATE PROCEDURE blah1(param1 INT UNSIGNED)BEGIN    CALL blah2(param1, 3);END;//CREATE PROCEDURE blah0()BEGIN    CALL blah1(4);END;//

Then, running this:

CALL blah(1, 1);CALL blah2(2, 2);CALL blah1(3);CALL blah0();

will return:

+--------+--------+| param1 | param2 |+--------+--------+|      1 |      1 |+--------+--------+1 row in set (0.00 sec)Query OK, 0 rows affected (0.00 sec)+--------+--------+| param1 | param2 |+--------+--------+|      2 |      2 |+--------+--------+1 row in set (0.00 sec)Query OK, 0 rows affected (0.00 sec)+--------+--------+| param1 | param2 |+--------+--------+|      3 |      3 |+--------+--------+1 row in set (0.00 sec)Query OK, 0 rows affected (0.00 sec)+--------+--------+| param1 | param2 |+--------+--------+|      4 |      3 |+--------+--------+1 row in set (0.00 sec)Query OK, 0 rows affected (0.00 sec)

Then, if you make sure to only use the blah2(), blah1() and blah0() procedures, your code will not need to be immediately updated, when you add a third parameter to the blah() procedure.


Viewing all articles
Browse latest Browse all 7

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>