Increment multiple Timestamp values by setting the incremented value in a user-defined variable in SQL


The incremented value can be set in a user-defined variable as shown below. Here, “yourValue” is the incremented value. After that, use MySQL UPDATE to update the column and increment timestamp values −

set @anyVariableName :=yourValue;
update yourTableName set yourColumnName=yourColumnName+interval (@yourVariableName) second;

Let us first create a table −

mysql> create table DemoTable
(
   DueDatetime timestamp
);
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2019-01-31 12 :30 :40');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('2019-09-06 10 :00 :00');
Query OK, 1 row affected (0.73 sec)
mysql> insert into DemoTable values('2019-09-07 11 :10 :24');
Query OK, 1 row affected (0.25 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------------------+
| DueDatetime       |
+-----------------------+
| 2019-01-31 12 :30 :40 |
| 2019-09-06 10 :00 :00 |
| 2019-09-07 11 :10 :24 |
+-----------------------+
3 rows in set (0.00 sec)

Following is the query to increment multiple timestamp values −

mysql> set @secondValue :=12;
Query OK, 0 rows affected (0.00 sec)
mysql> update DemoTable set DueDatetime=DueDatetime+interval (@secondValue) second;
Query OK, 3 rows affected (0.99 sec)
Rows matched : 3 Changed : 3 Warnings : 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output. The timestamp values are now incremented −

+-----------------------+
| DueDatetime           |
+-----------------------+
| 2019-01-31 12 :30 :52 |
| 2019-09-06 10 :00 :12 |
| 2019-09-07 11 :10 :36 |
+-----------------------+
3 rows in set (0.00 sec)
raja
Published on 07-Oct-2019 15:47:31
Advertisements