
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Scope of Variables Inside MySQL Stored Procedure
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)
Advertisements