How can we store a value in user-defined variable?


We can store a value in a user-defined variable in a statement and then refer to it afterward in other statements. Followings are the ways to store a value in user-defined variable −

With SET statement

we can store a user-defined variable by issuing a SET statement as follows −

Syntax

SET @var_name = expr[, @var_name = expr]…

In this @var_name is the variable name which consists of alphanumeric characters from current character set. We can use either = or := assignment operator with SET statement.

For example following queries can store the user variables with SET statement −

mysql> SET @value = 500;
Query OK, 0 rows affected (0.00 sec)

mysql> SET @value := 500;
Query OK, 0 rows affected (0.00 sec)

mysql> SET @value = 500, @value1=550;
Query OK, 0 rows affected (0.00 sec)

Without SET statement

Without the SET statement, we can also assign a value to a user variable in statements as follows −

mysql> select @value,@value1, @value2 := @value+@value1;

+--------+---------+---------------------------+
| @value | @value1 | @value2 := @value+@value1 |
+--------+---------+---------------------------+
| 500    | 550     | 1050                      |
+--------+---------+---------------------------+
1 row in set (0.00 sec)

In this case, we must have to use := assignment operator.

Updated on: 20-Jun-2020

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements