为什么我的存储过程在相同的日期工作?

时间:2016-01-16 13:13:06

标签: sql sql-server tsql sql-server-2012

为什么我的存储过程在我传递相同日期时没有工作(即From和To日期相同)虽然我有这些日期的记录,但它没有。为什么?

 SELECT
     Audits.pk_Audits_AuditID, 
     Audits.fk_WebUsers_Audits_UserID, 
     Web_Users.Name as UserName, 
     Districts.pk_Districts_DistrictID,
     Districts.DistrictName, 
     Orgs.pk_Orgs_OrgID, Orgs.OrgName, 
     Audits.AuditsUserActivity, 
     Audits.AuditsUserIPAddress,
     Audits.AuditsUserSystemMacAddress, 
     CONVERT(varchar, Audits.AuditSystemEntryDateTime, 113) AS AuditSystemEntryDateTime
FROM 
    Audits
INNER JOIN
    Web_Users ON Web_Users.UserID= Audits.fk_WebUsers_Audits_UserID
INNER JOIN
    Orgs ON Orgs.pk_Orgs_OrgID= Web_Users.fk_Orgs_OrgID_WebUsers
INNER JOIN
    Districts ON Districts.pk_Districts_DistrictID= Orgs.fk_Districts_Orgs_DistrictID
WHERE
    CONVERT(varchar, DateAdd(DAY, -1, Audits.AuditSystemEntryDateTime)) >= @FromDate
    AND CONVERT(varchar, Audits.AuditSystemEntryDateTime) <= @ToDate

1 个答案:

答案 0 :(得分:1)

它不起作用,因为你的AuditSystemEntryDateTime可能有时间。我怀疑你想要逻辑:

 Where CONVERT(date, DateAdd(DAY, -1, Audits.AuditSystemEntryDateTime)) >= @FromDate and
       CONVERT(date, Audits.AuditSystemEntryDateTime) <= @ToDate

通常,您不希望将datetime转换为除输出之外的任何其他用途的字符。

但是,编写这种逻辑的更好方法是:

where Audits.AuditSystemEntryDateTime >= dateadd(day, 1, @FromDate) and
      Audits.AuditSystemEntryDateTime < dateadd(day, 1, @ToDate)

通过将所有函数保留在常量上,SQL Server可以使用where子句的索引。嗯,添加一天也可以解释为什么你没有得到任何结果。也许你只是想要:

where Audits.AuditSystemEntryDateTime >= @FromDate and
      Audits.AuditSystemEntryDateTime < dateadd(day, 1, @ToDate)

这真的是最有意义的。