What do you mean MySQL user variables and how can we assign values to them?

MySQLMySQLi Database

MySQL user variables are written as @variable and it may be set to an integer, real, string or NULL value. With the help of SET statement, we can assign a value to the user variable. We can use either = or := as the assignment operator while assigning the values to user variables.

Example

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

mysql> Set @B = 'MySQL';
Query OK, 0 rows affected (0.00 sec)

The above queries have assigned the values 100 to user variable A and ‘MySQL’ to user variable B respectively.

We can check for their values with the help of SELECT statements as follows −

mysql> Select @A, @B;
+------+-------+
| @A   | @B    |
+------+-------+
| 100  | MySQL |
+------+-------+
1 row in set (0.05 sec)

We can also perform multiple variable assignments, separated by commas. It is illustrated in the following example −

mysql> SET @X = 'Ram',@Y = 'Shyam',@Z = 'Students', @S = 5000;
Query OK, 0 rows affected (0.00 sec)

mysql> Select @X, @Y, @Z, @S;
+------+-------+----------+------+
| @X   | @Y    | @Z       | @S   |
+------+-------+----------+------+
| Ram  | Shyam | Students | 5000 |
+------+-------+----------+------+
1 row in set (0.00 sec)

We can also assign values to them with SELECT statement but for that, we must have to use only := assignment operator and not =. It is illustrated in the example below −

mysql> SELECT @C := 'Tutorialspoint';
+------------------------+
| @C := 'Tutorialspoint' |
+------------------------+
| Tutorialspoint         |
+------------------------+
1 row in set (0.00 sec)

mysql> SELECT @C;
+----------------+
| @C             |
+----------------+
| Tutorialspoint |
+----------------+
1 row in set (0.00 sec)
raja
Published on 20-Feb-2018 15:16:08
Advertisements