Adding integers from a variable to a MySQL column?


To set a variable, use MySQL SET. For adding integers from a variable, use UPDATE and SET as in the below syntax −

set @anyVariableName:=yourValue;
update yourTableName set yourColumnName=yourColumnName+ @yourVariableName;

Let us first create a table −

mysql> create table DemoTable
-> (
-> Number int
-> );
Query OK, 0 rows affected (0.68 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values(60);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------+
| Number |
+--------+
| 10     |
| 20     |
| 40     |
| 60     |
+--------+
4 rows in set (0.00 sec)

Following is the query to add integers from a variable to MySQL column −

mysql> set @intValue:=100;
Query OK, 0 rows affected (0.00 sec)

mysql> update DemoTable set Number=Number+ @intValue;
Query OK, 4 rows affected (0.15 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Let us check table records once again −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------+
| Number |
+--------+
| 110    |
| 120    |
| 140    |
| 160    |
+--------+
4 rows in set (0.00 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

581 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements