试图通过运算符比较SQL Server中的时间

时间:2016-04-01 08:24:32

标签: sql sql-server database

我尝试将MS SQL Server中的日期与运算符进行比较,但我收到错误:

  

数据类型时间和日期时间与大于的不兼容   操作

Select *
from Student
where Student# not in(
    Select distinct Student#
    from Enrolls
    inner join Section on Enrolls.Section# = Section.se# 
    where section_time > DATEADD(year, -2, GETDATE())
      And Count(distinct student#) > 6);

我尝试过转换为变量,但后来这些变量未定义或定义不正确。这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

显然,section_time的数据类型时间

表达式DATEADD(year, -2, GETDATE())的数据类型为日期时间

您的代码没有意义,因为您将时间(仅包含“当天时间”)与两年前的日期(和时间)进行比较。什么是

11:30 > 2014-04-01 09:24

应该回来?

答案 1 :(得分:1)

将'CAST'用作Time数据类型

 Select * from Student where Student# not in(
 Select distinct Student# from Enrolls inner join Section on
 Enrolls.Section#=Section.se# 
 where section_time > CAST(DATEADD(year, -2, GETDATE()) AS TIME)
 And
 Count(distinct student#) > 6);