Wednesday, 25 July 2018

MySQL: Procedure Variable vs Session specific User Defined Variable (@variable vs variable)

I found lots of questions and discussions on the difference between stored procedure local variable and session-specific user-defined variable of MySQL.
MySQL provides session specific user defined variable to initialize and use during the session.
The scope of this variable is for the specific session only and outside of that session another client connection cannot access this variable and once session terminates, it destroys automatically.
This is loosely typed variables and we can initialize somewhere in a session.
We can write @var_name to define a session specific variable.
We also have one local variable, which we can define and use for specific stored objects like a stored procedure.
The scope of this local variable is for that object execution purpose. Once a stored procedure executes, it destroys automatically.
Below is a small demonstration on use of @variable vs variable:
Create a sample stored procedure with session and local variable:
You can check the above result, where @MyVariable is incrementing because it persists values until session end.
A stored procedure local variable is not incrementing because it destroyed after every execution of the stored procedure.

0 comments:

Post a Comment