我有一个用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,@dtexcludeThru
将是7:15
答案 0 :(得分: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
答案 1 :(得分:0)