比较SQL中的两个时间字符串

时间:2014-03-28 18:45:25

标签: sql sql-server datetime sql-server-2005

我有一个表示时间的字符串变量:

@time = '5:00 PM'

我需要检查当前时间getdate()是否在@time之后。我怎样才能在SQL中执行此操作?

3 个答案:

答案 0 :(得分:3)

一种方式,但在性能上并不是很好。

declare @time varchar(20)
set @time = '5:00pm'
select DatePart(hh,GETDATE())*60+DATEPART(mm,getDate()) as CurTime,
       DatePart(hh,@time)*60+DATEPART(mm,@time) as TheTime

答案 1 :(得分:2)

这应该这样做:

SQL 2008 +

if datediff(ss,cast(@time as time),cast(GetDate() as time)) < 0
   print 'Future'
else
   print 'Past'

早些时候:

if DatePart(hh,GETDATE())*60+DATEPART(mm,getDate()) < DatePart(hh,@time)*60+DATEPART(mm,@time)   
   print 'Future' 
else   
   Print 'Past'

答案 2 :(得分:0)

--@timeToCompare 在这里,替换你的字符串

Declare @timeToCompare time =CONVERT(varchar(20),CONVERT(time,'17:30:00'), 114);
Declare @Currenttime time= CONVERT(varchar(20),CONVERT(time,GETDATE()), 114);

--比较

if @timeToCompare > @Currenttime
 print 0
else
 print -1

你也可以使用 case when 条件。