如何在 MySQL 中声明一个日期时间变量?
要声明日期时间变量,你需要使用 SET 命令来使用用户定义的变量。其语法如下 -
SET @anyVariableName=’yourdatetimeValue’;
为了理解以上语法,让我们创建一个表。创建表的查询如下 -
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 命令在表中插入一些记录。插入记录的查询如下 -
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)
使用选择语句显示表中的所有记录。查询如下 -
mysql> select *from datetimeVariables;
以下是输出结果 -
+----+-------+---------------------+ | 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)
以下是使用 SET 命令声明日期时间变量的查询。查询如下 -
mysql> set @greaterThan2011Datetime='2012-04-25 15:30:25'; Query OK, 0 rows affected (0.00 sec)
以下是变量在选择查询中的用法。查询如下 -
mysql> select *from datetimeVariables -> where ArrivalDatetime> = @greaterThan2011Datetime;
以下是输出结果 -
+----+-------+---------------------+ | 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)
广告