MySQL--the difference between declare and set defined variables in a stored procedure

Source: Internet
Author: User
Tags prepare

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.