如何比较sql中的datetime对象 [英] how to compare datetime object in sql
本文介绍了如何比较sql中的datetime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较两个日期时间对象。
我的表
创建 表 [dbo]。[Table_1](
[id] [ int ] < span class =code-keyword> NOT NULL ,
[datevalue] [ datetime ] NOT NULL
) ON [ PRIMARY ]
insert into Table_1 值( 1 , convert ( datetime ,' 01/11/2014, 103 ))
insert into 表_1 值( 2 ,转换( datetime ,' 02 / 11/2014', 103 ))
insert into Table_1 values ( 3 ,转换( datetime ,' 03/12/2014', 103 ))
insert 进入表_1 值( 4 , convert ( datetime ,' 2014' 年4月12日, 103 ))
insert into Table_1 值( 5 , convert ( datetime ,' 05/12/2014' , 103 ))
声明 @ date nvarchar ( 10 );
set @ date = ' 03/12 / 2014'
选择 转换( varchar ( 10 ),datevalue, 103 )来自 Table_1
其中 convert ( varchar ( 10 ),datevalue, 103 )= convert( varchar ( 10 ), @ date , 103 )// 正确
但
set @ date = ' 01/12/2014'
选择 convert ( varchar ( 10 ),datevalue, 103 )来自 Table_1
其中 convert ( varchar ( 10 ),datevalue, 103 )> convert( varchar ( 10 ), @ date , 103 )
它给出
02/11/2014
03/12/2014
04/12/2014
05/12/2014
此查询应该是只提供三条记录
03/12/2014
04/12/2014
05/12/2014
解决方案
在比较时,切勿将日期格式转换为字符串。执行此操作时,日期表现为varchar值而不是日期,因此比较适用于varchar。
使用以下查询。
声明 @ date nvarchar (< span class =code-digit> 10 );
set @ date = ' 01/12 / 2014'
选择 转换( varchar ( 10 ),datevalue, 103 )来自 Table_1
其中 convert ( datetime ,datevalue, 103 )> convert( datetime , @ date , 103 )
希望它能解决你的问题问题
I want to compare two datetime object.
my table
CREATE TABLE [dbo].[Table_1](
[id] [int] NOT NULL,
[datevalue] [datetime] NOT NULL
) ON [PRIMARY]
insert into Table_1 values(1,convert(datetime,'01/11/2014',103))
insert into Table_1 values(2,convert(datetime,'02/11/2014',103))
insert into Table_1 values(3,convert(datetime,'03/12/2014',103))
insert into Table_1 values(4,convert(datetime,'04/12/2014',103))
insert into Table_1 values(5,convert(datetime,'05/12/2014',103))
declare @date nvarchar(10);
set @date='03/12/2014'
select convert(varchar(10),datevalue,103) from Table_1
where convert(varchar(10),datevalue,103)=convert(varchar(10),@date,103) //this is correct
but
set @date='01/12/2014'
select convert(varchar(10),datevalue,103) from Table_1
where convert(varchar(10),datevalue,103)>convert(varchar(10),@date,103)
it gives
02/11/2014
03/12/2014
04/12/2014
05/12/2014
this query should give only three records
03/12/2014
04/12/2014
05/12/2014
解决方案
Never convert the date formats to string whenever you are comparing. When you do this the date behaves as a varchar value rather than the date, hence the comparison works on varchar.
Use the following query.
declare @date nvarchar(10); set @date='01/12/2014' select convert(varchar(10),datevalue,103) from Table_1 where convert(datetime,datevalue,103)>convert(datetime,@date,103)
Hope it solves your problem.
这篇关于如何比较sql中的datetime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文