Increase and decrease row value by 1 in MySQL with Stored Procedure?

MySQLMySQLi Database

Let us first create a table to increase and adecrease row value by 1. The following is the query −

mysql> create table IncrementAndDecrementValue
   −> (
   −> UserId int,
   −> UserScores int
   −> );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into IncrementAndDecrementValue values(101,20000);
Query OK, 1 row affected (0.13 sec)

mysql> insert into IncrementAndDecrementValue values(102,30000);
Query OK, 1 row affected (0.20 sec)

mysql> insert into IncrementAndDecrementValue values(103,40000);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from IncrementAndDecrementValue;

The following is the output −

+--------+------------+
| UserId | UserScores |
+--------+------------+
|    101 |      20000 |
|    102 |      30000 |
|    103 |      40000 |
+--------+------------+
3 rows in set (0.00 sec)

Here is my stored procedure to increase and decrease row value by 1.

mysql> delimiter //

mysql> create procedure IncrementAndDecrementRowValueByOne()
   −> begin
   −> declare first int;
   −> declare second int;
   −> set first = (select UserScores from IncrementAndDecrementValue where UserId = 101);
   −> set second = (select UserScores from IncrementAndDecrementValue where UserId = 102);
   −> update IncrementAndDecrementValue set UserScores = first-1 where UserId = 101;
   −> update IncrementAndDecrementValue set UserScores = second+1 where UserId = 102;
   −> end //
Query OK, 0 rows affected (0.17 sec)

mysql> delimiter ;

Call the stored procedure using CALL command. The query is as follows −

mysql> call IncrementAndDecrementRowValueByOne();
Query OK, 1 row affected (0.24 sec)

Check the row value is updated or not using select statement. The query is as follows −

mysql> select *from IncrementAndDecrementValue;

The following is the output −

+--------+------------+
| UserId | UserScores |
+--------+------------+
|    101 |      19999 |
|    102 |      30001 |
|    103 |      40000 |
+--------+------------+
3 rows in set (0.00 sec)

We have decremented the value 20000 to 19999 and incremented 30000 to 30001.

raja
Published on 16-Jan-2019 09:18:53
Advertisements