选择涉及日期和时间之间比较的查询

时间:2013-03-04 12:02:59

标签: c# asp.net sql sql-server sql-server-2008

这是我的MS Sql表.. 表: http://snag.gy/L6ag1.jpg

SELECT 
    * 
FROM Table1 
WHERE   
    Class = '12' 
    AND Section = 'B' 
    AND '3/4/2013' BETWEEN DATE AND TODATE 
    and '3/14/2013' between Date and ToDate 
    or '3/4/2013' < Date and '3/14/2013' > ToDate 
    AND (
            '12:00 PM'  between [StartTime] and endtime 
            and '1:00 PM' between [StartTime] and endtime 
            or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)
        )

上面的查询返回表的所有6行,而下面的查询返回0行..

SELECT 
    * 
FROM Teacher 
WHERE   
    Class = '12' 
    AND Section = 'B' 
    and '12:00 PM'  between [StartTime] and endtime 
    and '1:00 PM' between [StartTime] and endtime 
    or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)

我期待顶部的查询返回0行,因为我使用AND操作数,所以即使日期比较返回行,组合查询也不应返回任何内容,因为时间比较返回false。

脚本创建表:

INSERT INTO [SLIITComDB].[dbo].[Teacher]
           ([TeacherId]
           ,[TeacherName]
           ,[Class]
           ,[Section]
           ,[SubjectId]
           ,[Date]
           ,[ToDate]
           ,[Day]
           ,[StartTime]
           ,[EndTIme]
           ,[Absent])
     VALUES
           (<TeacherId, int,>
           ,<TeacherName, varchar(50),>
           ,<Class, varchar(50),>
           ,<Section, varchar(50),>
           ,<SubjectId, varchar(50),>
           ,<Date, date,>
           ,<ToDate, date,>
           ,<Day, varchar(50),>
           ,<StartTime, time(7),>
           ,<EndTIme, time(7),>
           ,<Absent, varchar,>)
GO

2 个答案:

答案 0 :(得分:3)

在SQL中,AND运算符优先于OR运算符。

因此,在您的第一个查询中,条件如下所示:

WHERE   
  ( Class = '12' 
    AND Section = 'B' 
    AND '3/4/2013' BETWEEN DATE AND TODATE 
    and '3/14/2013' between Date and ToDate
   ) OR (
    '3/4/2013' < Date and '3/14/2013' > ToDate 
    AND (
            '12:00 PM'  between [StartTime] and endtime 
            and '1:00 PM' between [StartTime] and endtime 
            or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)
        ))

当顶部或底部(由TRUE分隔)为OR时,结果为TRUE

第二个查询中的条件也如下所示:

WHERE   
  ( Class = '12'
    AND Section = 'B' 
    and '12:00 PM'  between [StartTime] and endtime 
    and '1:00 PM' between [StartTime] and endtime
   )
    or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)

即使时间比较都是FALSE,您的第一个查询也可以返回结果,因为您的前两个日期比较可以是TRUE

答案 1 :(得分:1)

实际上是你的OR导致了这个:

根据您的数据,或之前的第一部分是真实的。所以这些将被退回。添加括号以澄清事情。

真:

 Class = '12' 
    AND Section = 'B' 
    AND '3/4/2013' BETWEEN DATE AND TODATE 
    and '3/14/2013' between Date and ToDate 

 OR

题:

'3/4/2013' < Date and '3/14/2013' > ToDate 
    AND (
            '12:00 PM'  between [StartTime] and endtime 
            and '1:00 PM' between [StartTime] and endtime 
            or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)
        )

试试这个简化:

select * 
from Table1 
where 1 = 1
or 2 = 2
and 1 = 3