0

我有一个与 Windows 调度程序一起自动运行的程序。该程序运行一个使用昨天日期的存储过程,对我们的数据库运行查询以提取前一天的结果。此查询不包括全天的特定时间段,因为我们不关心这些结果。但是,我们星期天有不同的时间,并且想更改星期天的查询……如果是“星期天”,有没有办法以不同的方式查询?下面是我的存储过程:

CREATE PROCEDURE [dbo].[sp_Open_Close_Report_1] AS
declare   @dtNow         datetime ,   @dtToday       datetime ,   @dtFrom        datetime ,   @dtThru        datetime ,   @dtExcludeFrom datetime ,   @dtExcludeThru datetime, @dtExcludeEOD 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 ) 
set @dtExcludeEOD = convert(datetime, convert(char(10),@dtFrom,120) + ' 08:00:00.000' , 120 ) 


SELECT Store_Id , DM_Corp_Received_Date, Register_Transaction_Type 
FROM Register_Till_Count_Tb 
WHERE (Register_Transaction_Type    =  'SOD' and store_ID = '12345'
AND DM_Corp_Received_date     between @dtFrom        
and @dtThru   
AND DM_Corp_Received_date not between @dtExcludeFrom 
and @dtExcludeThru) or (Register_Transaction_Type = 'EOD' and Store_ID='12345'
AND DM_Corp_Received_date Between @dtFrom and @dtThru)

周日@DTExclude从 6:30 到@dtexcludeThru7:15

4

2 回答 2

2

让我们做更多的数学运算,将所有内容保留为日期时间(或整数),而不是使用字符串:

declare   @dtNow         datetime ,   @dtToday       datetime ,   @dtFrom        datetime ,   @dtThru        datetime ,   @dtExcludeFrom datetime ,   @dtExcludeThru datetime, @dtExcludeEOD datetime 
set @dtNow         = getdate() 
set @dtToday       = DATEADD(day,DATEDIFF(day,0,@dtNow),0)
set @dtFrom        = dateadd(day,-1,@dtToday)

declare @Sunday int
set @Sunday = CASE WHEN DATEPART(weekday,@dtFrom) = DATEPART(weekday,'20120805') THEN 1 ELSE 0 END
set @dtExcludeFrom = DATEADD(minute,330 + @Sunday * 60,@dtFrom)
set @dtExcludeThru = DATEADD(minute,375 + @Sunday * 60,@dtFrom)
set @dtExcludeEOD = DATEADD(minute,480,@dtFrom)

而且,在您的查询中,而不是:

column between @dtFrom and @dtThru

采用:

column >= @dtFrom and column < @dtToday
于 2012-08-10T13:35:00.283 回答
0

看一下datenamedatepart函数。您可以使用if语句根据当天的情况执行不同的逻辑。在周日运行时,它们将产生以下结果:

select datename(dw, getdate()) -- Sunday
select datepart(dw, getdate()) -- 1
于 2012-08-10T13:28:23.330 回答