MySQL how to declare a datetime variable?

MySQLMySQLi Database

To declare a datetime variable, you need to use a user-defined variable using the SET command. The syntax is as follows −

SET @anyVariableName=’yourdatetimeValue’;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table datetimeVariables
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(10),
   -> ArrivalDatetime datetime,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.78 sec)

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

mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('John','2011-01-31 13:45:20');
Query OK, 1 row affected (0.53 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Sam','2012-04-25 15:30:25');
Query OK, 1 row affected (0.18 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Larry','2013-10-04 16:40:30');
Query OK, 1 row affected (0.10 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Bob','2014-05-15 10:30:25');
Query OK, 1 row affected (0.33 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Mike','2017-08-13 11:30:25');
Query OK, 1 row affected (0.08 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('David','2018-04-25 09:30:25');
Query OK, 1 row affected (0.20 sec)

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

mysql> select *from datetimeVariables;

The following is the output −

+----+-------+---------------------+
| Id | Name  | ArrivalDatetime     |
+----+-------+---------------------+
|  1 | John  | 2011-01-31 13:45:20 |
|  2 | Sam   | 2012-04-25 15:30:25 |
|  3 | Larry | 2013-10-04 16:40:30 |
|  4 | Bob   | 2014-05-15 10:30:25 |
|  5 | Mike  | 2017-08-13 11:30:25 |
|  6 | David | 2018-04-25 09:30:25 |
+----+-------+---------------------+
6 rows in set (0.00 sec)

The following is the query to declare the datetime variable using SET command. The query is as follows −

mysql> set @greaterThan2011Datetime='2012-04-25 15:30:25';
Query OK, 0 rows affected (0.00 sec)

The following is the use of a variable in a select query. The query is as follows −

mysql> select *from datetimeVariables
   -> where ArrivalDatetime> = @greaterThan2011Datetime;

The following is the output −

+----+-------+---------------------+
| Id | Name  | ArrivalDatetime     |
+----+-------+---------------------+
|  2 | Sam   | 2012-04-25 15:30:25 |
|  3 | Larry | 2013-10-04 16:40:30 |
|  4 | Bob   | 2014-05-15 10:30:25 |
|  5 | Mike  | 2017-08-13 11:30:25 |
|  6 | David | 2018-04-25 09:30:25 |
+----+-------+---------------------+
5 rows in set (0.00 sec)
raja
Published on 26-Feb-2019 11:23:08
Advertisements