SQL自动选择日期范围基于今天的星期几

时间:2014-07-17 08:28:58

标签: sql parameters date-range sql-date-functions

- 这是使用SQL

我曾经尝试过几次失败,

我的销售表格的订购日期格式为“2014-05-15 00:00:00.000”

我希望有一个报告,基于如果@today小于星期五,显示上周的日期范围,如果@today是星期六或星期日,那么使用这个星期日期范围

假设我只想查看字段SalesOrder和OrderDate

提前致谢,

迪安

1 个答案:

答案 0 :(得分:2)

调整您的内容(在SQL Server Management Studio中运行此内容将显示具有正确输出的消息)。使用变量过滤SELECT语句并删除PRINT运算符:

DECLARE @ReportDate DATETIME
DECLARE @StartOfWeek DATETIME
DECLARE @DayOfWeek INT 

SET @ReportDate = '2014-05-15 00:00:00.000' --This will be your variable in report builder
SET @DayOfWeek = DATEPART(dw,@ReportDate)

/* 
Take away the day of the week from the report date to
get the beginning of that week.
*/

--Adjust the +1 to mark the start of your week (ie. +2 makes Monday the start)
SET @StartOfWeek = DATEADD(dd, (-(@DayOfWeek) + 1), @Reportdate)

--Now do stuff based on the report date (set the beginning of the week)
IF @DayOfWeek BETWEEN 2 AND 5 --Friday is day 6 (Sunday is first day in SQL and the BETWEEN clause is inclusive)
BEGIN
    PRINT 'Monday to Thursday' --This line can be removed
    /* Now minus 7 to get the beginning of the previous week */
    SET @StartOfWeek = DATEADD(dd, -7, @StartOfWeek)
END
---------------------------------------------------
/*
This entire box is optional (can be removed) but just for demonstration purposes to
show that the date stuff works
*/

IF @DayOfWeek = 6 --Friday is day 6 
BEGIN
    PRINT 'Friday'
END
IF @DayOfWeek IN (7,1) --Saturday day 7, Sunday day 1
BEGIN
    PRINT 'Saturday or Sunday'
END
---------------------------------------------------

--This is where your SELECT statement goes (instead of PRINT operators below)
PRINT 'StartOfWeek = ' + CAST(@StartOfWeek AS NVARCHAR(255))
PRINT 'EndOfWeek = ' + CAST(DATEADD(dd,7,@StartOfWeek) AS NVARCHAR(255))