mssql sqlserver “between and 关键字”在”日期范围”使用中注意事项说明


摘要:
下文讲述between and 关键字的使用注意事项,如下所示:
实验环境:sql server 2008 R2



between and 关键字用法说明

between and 关键字应用包含范围的数据,between and会包含左右边界的数据;
between and 关键字常用于日期、数值类型数据的范围检索。
下文着重讲述between and关键字在包含日期范围时的注意事项,如下所示:



between and 关键字注意事项


between and 日期范围注意事项1:

   create table [maomao365.com]
 (keyId int identity(1,1),
  info  varchar(30),
  writeDate datetime
  )
  go
  ----生成基础数据
  insert into [maomao365.com]
  (info,writeDate)
  values
  (N'sqlserver','2019-06-24 13:01:34'),
  (N'sql爱好者','2019-06-24 09:01:34'),
   (N'猫猫小屋','2019-06-24 23:01:34')
   go
   /* 
   between and误区一:
      日期字段会默认加入0:00:00的边界范围,
      短日期类型,在between and的应用时,会自动在日期的边界上加上时间 0:00:00 
   如下例所示:
      将不会展示出任何数据
   */ 
    
   select  * from [maomao365.com] 
   where writeDate between '2019-6-24' and '2019-6-24'
    
   ---修正方法1: 修改writeDate为短日期,然后进行between and计算
    select   * from [maomao365.com] 
       where convert(datetime,convert(varchar(20),writeDate,23))  between '2019-6-24' and '2019-6-24'
    
     
   ---修正方法2:加边界加上左右时间
     select  * from [maomao365.com] 
       where writeDate between '2019-6-24 0:00:00' and '2019-6-24 23:59:59'
      
  go
  truncate table [maomao365.com]
  drop     table [maomao365.com]