What do you mean by Scope of variables inside MySQL stored procedure?

MySQLMySQLi Database

Suppose if we declare a variable inside a BEGIN/END block then the scope of this variable would be in this particular block. We can also declare a variable with the same name inside another BEGIN/END block which will be totally legal but its scope would be inside its BEGIN/END block. It can be understood with the help of the following example in which we are creating a procedure to show the scope of the variables −

Example

mysql> Create Procedure Scope_variables()
    -> BEGIN
    -> DECLARE A Varchar(5) Default 'outer';
    -> BEGIN
    -> DECLARE A Varchar(5) Default 'inner';
    -> SELECT A;
    -> END;
    -> SELECT A;
    -> END;
    -> //
Query OK, 0 rows affected (0.08 sec)

In the above procedure, we have two variables with the same name i.e. A. Here the inner variable declaration takes precedence as long as it is in scope. The point is that the inner variable disappears when the first END is reached and it is called ‘OUT OF SCOPE’. To understand the concept invoke this procedure as follows −

mysql> CALL Scope_variables();
+-------+
| A     |
+-------+
| inner |
+-------+
1 row in set (0.00 sec)

+-------+
| A     |
+-------+
| outer |
+-------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)
raja
Published on 21-Feb-2018 15:41:47
Advertisements