为什么日期不是 13/09/2016

Why date is not taking 13/09/2016

我正在检查 12/09/201613/09/2016 的条件,但它没有显示 13/09/2016 的数据并给出错误

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

这是我的查询

SELECT DISTINCT  
   b.mkey ,  a.N_UserMkey, cuser_id,isnull(a.N_UserMkey,cuser_id) aa,
   ISNULL(b.first_name + ' ', '')  
   + ISNULL(b.last_name, '') NAME, convert(varchar,a.U_datetime,103) Action_Date
  FROM      inward_doc_tracking_trl a  
   INNER JOIN user_mst b ON isnull(a.N_UserMkey,cuser_id) = b.mkey  
  WHERE 
  convert(datetime,a.U_datetime,103) 
    BETWEEN convert(varchar,'12/09/2016',103)
  AND convert(varchar,'13/09/2016',103)
   and b.mkey=2357

您需要转换为 DATETIME

...
BETWEEN convert(datetime,'12/09/2016',103)
  AND convert(datetime,'13/09/2016',103)

目前查询只是将 BETWEEN 参数保留为 VARCHAR,然后服务器需要将它们与 convert(datetime,a.U_datetime,103) 进行比较。在那一刻,它们被转换为没有指定格式的 DATETIME。

我不确定,但您似乎在这里犯了几个错误:

  • 不检查 BETWEEN 的日期范围。由于日期时间的时间部分,这是非常错误的。经常被遗忘......你可能 read this great blog by Aaron Betrand
  • 切勿在特定于文化的格式中使用文字日期。你可能 read this (and other answers there)
  • 始终按需要的类型比较数据。您将日期转换为字符串只是为了比较它们 字母数字?
  • convert(varchar,'12/09/2016',103) 中您使用的 varchar 没有长度... One more bad habit to kick

尝试将您的 WHERE 子句更改为此(所有日期时间均为 9 月 12 日,但不是 13 日)

WHERE a.U_datetime >= {d'2016-09-12'} AND a.U_datetime<{d'2016-09-13'}

或这个(9 月 12 日和 13 日的所有日期时间)

WHERE a.U_datetime >= {d'2016-09-12'} AND a.U_datetime<{d'2016-09-14'}