要声明日期时间变量,您需要使用SET命令使用用户定义的变量。语法如下-
SET @anyVariableName=’yourdatetimeValue’;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table datetimeVariables -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(10), -> ArrivalDatetime datetime, -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。插入记录的查询如下-
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('John','2011-01-31 13:45:20'); mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Sam','2012-04-25 15:30:25'); mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Larry','2013-10-04 16:40:30'); mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Bob','2014-05-15 10:30:25'); mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Mike','2017-08-13 11:30:25'); mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('David','2018-04-25 09:30:25');
使用select语句显示表中的所有记录。查询如下-
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命令声明datetime变量的查询。查询如下-
mysql> set @greaterThan2011Datetime='2012-04-25 15:30:25';
以下是选择查询中变量的使用。查询如下-
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)