Declaring variables
To declare a variable inside a stored procedure, you use theDECLARE statement as follows:- First, you specify the variable name after the
DECLAREkeyword. The variable name must follow the naming rules of MySQL table column names. - Second, you specify the data type of the variable and its size. A variable can have any MySQL data types such as
INT,VARCHAR,DATETIME, etc. - Third, when you declare a variable, its initial value is
NULL. You can assign the variable a default value by usingDEFAULTkeyword.
total_sale with the data type INT and default value 0 as follows:DECLARE statement as following:INT variables x and y , and set their default values to zero.Assigning variables
Once you declared a variable, you can start using it. To assign a variable another value, you use theSET statement, for example:total_count variable is 10 after the assignment.Besides the
SET statement, you can use SELECT INTO statement to assign the result of a query to a variable. Notice that the query must return a scalar value.- First, we declare a variable named
total_productsand initialize its value to0. - Then, we used the
SELECT INTOstatement to assign thetotal_productsvariable the number of products that we selected from the products from theproductstable.
Variables scope
A variable has its own scope, which defines its life time. If you declare a variable inside a stored procedure, it will be out of scope when theEND statement of stored procedure reached.If you declare a variable inside
BEGIN END block, it will be out of scope if the END is reached. You can declare two or more variables with the same name in different scopes because a variable is only effective in its own scope. However, declaring variables with the same name in different scopes is not good programming practice.A variable that begins with the
@ sign at the beginning is session variable. It is available and accessible until the session ends.
No comments:
Post a Comment