【问题标题】:Compare two time strings in SQL比较 SQL 中的两个时间字符串
【发布时间】:2014-05-08 09:17:16
【问题描述】:

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

@time = '5:00 PM'

我需要检查当前时间getdate() 是在@time 之后还是之前。如何在 SQL 中做到这一点?

【问题讨论】:

  • 旁注;如果你需要良好的性能,那你就存储错了。
  • 在sql中比较两次需要float转换:stackoverflow.com/questions/807909/…
  • @JoachimIsaksson 我同意,但不幸的是我正在处理我无法更改的依赖代码......

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


【解决方案1】:

一种方式,但性能不佳。

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

【讨论】:

  • 适用于早期服务器版本的良好解决方案。
【解决方案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'

【讨论】:

  • 您确实需要添加一条语句,在比较成功或失败时执行。
  • 如果getdate的时间早于@time,这将返回true?谢谢
  • 如果第二个参数在第三个之前,你会得到一个肯定的结果。如果第二个参数晚于第三个参数,则为负数。因此,如果您的@time 在 GetDate() 之后,则 datediff() 值将为负数。
  • 我收到一个错误:类型时间不是定义的系统类型。我正在使用 SQL Server 2005。
  • 时间实际上是 2008+ 数据类型。我已将我的答案与 Sparky 的答案结合起来,以便与早期版本进行比较。
【解决方案3】:

--@timeToCompare here,替换你的字符串

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

条件时也可以使用大小写。

【讨论】:

    猜你喜欢
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多