代码之家  ›  专栏  ›  技术社区  ›  F11

显示错误结果的Sql Server表日期查询

  •  0
  • F11  · 技术社区  · 7 年前

    我有一个Sql server表,其中包含以下日期值(10月4日)

    enter image description here

    现在下面的查询没有显示任何结果

      select 
                *
            from [dbo].[TB_AUDIT] TBA 
    
            where   TBA.ActionDate >= '10/01/2018' and TBA.ActionDate <= '10/04/2018' which is not correct.
    

    选择 * 来自[dbo].[TB\U AUDIT]待定

        where   TBA.ActionDate >= '10/01/2018' and TBA.ActionDate <= '10/05/2018' it is returning me all results.
    

    我做错了什么。

    4 回复  |  直到 7 年前
        1
  •  3
  •   Panagiotis Kanavos    7 年前

    日期 格式为 YYYYMMDD . YYYY-MM-DD 它本身可能无法在SQL server中工作,因为它仍然受该语言的影响。ODBC日期文本, {d'YYYY-MM-DD'}

    其次,日期参数没有默认为的时间 00:00 . 但是,存储的日期有一个时间元素,这意味着它们不在搜索范围内,即使可以识别日期参数。

    select 
            *
    from [dbo].[TB_AUDIT] TBA 
    where   
        cast(TBA.ActionDate as date) between '20181001' and '20181004'
    

        cast(TBA.ActionDate as date) between {d'2018-10-01'} and {d'2018-10-04'}
    

    通常,将函数应用于字段会阻止服务器使用任何索引。SQLServer非常聪明,可以将其转换为覆盖整个日期的查询,本质上类似于

    where   
        TBA.ActionDate >='2018:10:01T00:00' and TBA.ActionDate <'2018-10-05T00:00:00'
    
        2
  •  3
  •   Eric Brandt    7 年前

    当您没有为 DATETIME ,SQL Server默认为午夜。所以在第一个查询中,您需要所有结果 <='2018-10-04T00:00:00.000' 更大的 '2018-10-04T00:00:00.000'

    你想要什么

    TBA.ActionDate >= '2018-10-01T00:00:00.000' and TBA.ActionDate < '2018-10-05T00:00:00.000'`
    
        3
  •  1
  •   Gordon Linoff    7 年前

    使用格式正确的日期!

    select *
    from [dbo].[TB_AUDIT] TBA 
    where TBA.ActionDate >= '2018-10-01' and TBA.ActionDate <= '2018-10-04' 
    

        4
  •  0
  •   lije    7 年前