There are two ways to define variables in a MySQL stored procedure:
1. Use set or select to assign a value directly, and the variable name begins with @.
For example: Set @var = 1;
You can declare anywhere in a session that the scope is the entire session, called the session variable.
2. Variables declared with the DECLARE keyword can only be used in stored procedures, called stored procedure variables, such as:
DECLARE var1 INT DEFAULT 0;
It is used primarily in stored procedures, or in storage-pass parameters.
The difference between the two is:
Variables declared with declare are initialized to NULL when the stored procedure is called. The session variable (that is, the variable at the start of the @) is not reinitialized, in a session, it is initialized only once, and then within the session is the result of the last calculation, which is equivalent to the global variable within the session.
In a stored procedure, dynamic content must be assigned to a session variable when it is preprocessed using dynamic statements.
Cases:
Set @v_sql = SQLText;
PREPARE stmt from @v_sql;
EXECUTE stmt;
Deallocate PREPARE stmt;
MySQL--the difference between declare and set defined variables in a stored procedure