How is the declare statement used in MySQL?
In MySQL, the DECLARE statement is used to declare a local variable or cursor. Its syntax is as follows:
Create a variable called variable_name of type datatype with an optional initial value.
Among them:
- variable_name: name of the variable.
- Datatype: The type of data that a variable can hold, such as integers, floating-point numbers, strings, etc.
- DEFAULT: Optional, used to specify an initial value for a variable.
- initial_value: The initial value of a variable.
Example:
I am going to the store to buy some groceries.
Set the default value of the variable @id to 1 and declare the variable @name with a maximum length of 50 characters.
In the example above, we have declared two variables: @id and @name. @id is a variable of integer type with an initial value of 1. @name is a variable of string type without a specified initial value.
Please note that the DECLARE statement can only be used in stored procedures, functions, or triggers and cannot be used in query statements.