Using Declare statement to declare the local variable : Variable Scope « Procedure Function « MySQL Tutorial






mysql>
mysql> DELIMITER //
mysql>
mysql> CREATE FUNCTION myFunction (cost DECIMAL(10,2)) RETURNS DECIMAL(10,2)
    -> BEGIN
    ->
    ->     DECLARE shipping_cost DECIMAL(10,2);
    ->
    ->     SET shipping_cost = 0;
    ->     IF cost < 25.00 THEN
    ->             SET shipping_cost = 10.00;
    ->     ELSEIF cost < 100.00 THEN
    ->             SET shipping_cost = 20.00;
    ->     ELSEIF cost < 200.00 THEN
    ->             SET shipping_cost = 30.00;
    ->
    ->     ELSE
    ->             SET shipping_cost = 40.00;
    ->     END IF;
    ->
    ->     RETURN shipping_cost;
    -> END
    -> //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;
mysql>
mysql> select myFunction(123.123);
+---------------------+
| myFunction(123.123) |
+---------------------+
|               30.00 |
+---------------------+
1 row in set, 1 warning (0.02 sec)

mysql>
mysql> drop function myFunction;
Query OK, 0 rows affected (0.00 sec)








11.11.Variable Scope
11.11.1.LOCAL, SESSION, AND GLOBAL VARIABLES IN MYSQL
11.11.2.Variable scope
11.11.3.Inner variable shadows the outter variable
11.11.4.Nested blocks
11.11.5.Using Declare statement to declare the local variable