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:

  1. variable_name: name of the variable.
  2. Datatype: The type of data that a variable can hold, such as integers, floating-point numbers, strings, etc.
  3. DEFAULT: Optional, used to specify an initial value for a variable.
  4. 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.

bannerAds