问题
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