关于日期和时间的SQL查询

时间:2013-09-18 11:27:23

标签: sql sql-server

我想回答以下问题:

显示2007年10月从中午到下午5点开始的所有活动

我尝试了以下查询:

SELECT EngagementNumber, StartDate, StartTime
FROM Engagements
WHERE StartDate <= CAST('2007-10-31' As DATE)
AND EndDate >= CAST('2007-10-01' AS DATE)
AND StartTime Between CAST('12:00:00' AS TIME) AND CAST('17:00:00' AS TIME)

但是,发生以下错误:

  

Msg 402,Level 16,State 1,Line 1   数据类型datetime和time在小于或等于运算符时不兼容。

我在SQL Server数据库2008R2版本上运行它,并想知道是否有人能告诉我为什么会这样做?

由于

3 个答案:

答案 0 :(得分:2)

SELECT 
       EngagementNumber, 
       StartDate, 
       StartTime
FROM 
       Engagements
WHERE
      StartDate <= '2007-10-31' 
      AND EndDate >= '2007-10-01' 
      AND convert(char(8), StartTime , 108) BETWEEN '12:00:00' AND '17:00:00'

108常量输出为hh:mm:ss

答案 1 :(得分:1)

试试这种方式

SELECT  EngagementNumber, StartDate, StartTime 
FROM    Engagements
WHERE   StartDate <= '2007-10-31T12:00:00.000' 
  AND   EndDate >=  '2007-10-01T17:00:00.000'

如果startdate和enddate是datetime数据类型

,这将有效

答案 2 :(得分:0)

我只会使用datepart(hour)

SELECT EngagementNumber, StartDate, StartTime
FROM Engagements
WHERE StartDate <= CAST('2007-10-31' As DATE) AND
      EndDate >= CAST('2007-10-01' AS DATE) and
      datepart(hour, StartTime) >= 12 and datepart(hour, EndTime) < 17;