更好的写 SQL where 子句的方法

Better way to write SQL where clause with date

我正在 运行宁 SQL 声明,如下所示。这最终将用于每晚用天交易填充报告 table。当我 运行 它没有

Cast(M._CreateDateTime as Date) = @StartDate

需要1:40。 将函数返回到 where 子句中需要 10 多分钟。

Declare @StartDate DAte = GetDate()

If Object_ID ('tempdb.dbo.#WinBack') is not null Drop Table #WinBack

Select
  M.HospitalMasterID
  ,M.TxnSite
  ,P.ClientID
  ,M.PatientID
  ,M.TxnDate as CallDate
  ,M.TxnCode
  ,M.EnteredMasterID
  ,U.UserName
  ,U.UserDept
Into
  #WinBack
From
  Avimark_OLTP.dbo.MedicalHistory as M
  Inner JoinAvimark_OLTP.dbo.Patient as P on
    M.HospitalMasterID = P.HospitalMasterID and
    M.PatientID = P.PatientID
  Left Outer Join RptSys.dbo.Ref_User as U on
    M.EnteredMasterID = U.UserMastID
Where
  Cast(M._CreateDateTime as Date) = @StartDate and
  M.TxnCode = 'RemCall' and
  U.UserName is not null

有人对如何加快速度有什么建议吗?我知道是演员在扼杀它。

谢谢,

对列使用函数使得 SQL 服务器同时转换 table 中的每一行,它正在比较和防止索引使用,你应该这样做:

Declare @StartDate Date, @EndDate Date

set @StartDate = GetDate()
set @EndDate = dateadd(day, 1, @StartDate)

select 
   ... 
where 
    M._CreateDateTime >= @StartDate and 
    M._CreateDateTime < @endDate