Exclude a specific range of time in a stored procedure

旧城冷巷雨未停 提交于 2019-12-13 07:26:23

问题


I have a stored procedure that queries my database to pull a "Open" report for "Yesterdays" date. This program will run on windows scheduler always querying the database for yesterdays results. I want all of the results from yesterday EXCEPT 5:30AM - 6:26AM. I do not care to see these results... Everything works, with the exception of not displaying the specified time block...

My stored procedure is:

ALTER PROCEDURE [dbo].[Open_Close] AS
declare   @dtNow         datetime ,   @dtToday       datetime ,   @dtFrom        datetime ,   @dtThru        datetime ,   @dtExcludeFrom datetime ,   @dtExcludeThru datetime  
set @dtNow         = getdate() 
set @dtToday       = convert(datetime,convert(varchar,@dtNow,112),112) 
set @dtFrom        = dateadd(day,-1,@dtToday) -- start-of-day yesterday 
set @dtThru        = dateadd(ms,-3,@dtToday)  -- end-of-day yesterday (e.g., 2012-06-17 23:59:59.997) 
set @dtExcludeFrom = convert(datetime, convert(char(10),@dtFrom,120) + ' 05:30:00.000' , 120 ) 
set @dtExcludeThru = convert(datetime, convert(char(10),@dtFrom,120) + ' 06:15:00.000' , 120 )  

SELECT Store_Id , DM_Corp_Received_Date
FROM Register_Till_Count_Tb 
WHERE Register_Transaction_Type    =  'SOD'   
AND Register_Till_Count_Datetime     between @dtFrom        
and @dtThru  AND Register_Till_Count_Datetime not between @dtExcludeFrom 
and @dtExcludeThru

回答1:


Try changing

Register_Till_Count_Datetime not between @dtExcludeFrom and @dtExcludeThru

to

 (Register_Till_Count_Datetime < @dtExcludeFrom  OR 
  Register_Till_Count_Datetime > @dtExcludeThru)

Don't forget the parentheses.

The NOT BETWEEN doesn't always work as you would expect.




回答2:


Try

AND NOT (Register_Till_Count_Datetime between @dtExcludeFrom and @dtExcludeThru )


来源:https://stackoverflow.com/questions/11886769/exclude-a-specific-range-of-time-in-a-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!