Question

I need to show N records with each record being 1 weeks worth of summarized data. One of the inputs will be a date range.

Since each week should start with monday, I want to get a list of all the monday dates in the date range. Any suggestions to get that? Note: This has to run on SQL 2005

declare @dt datetime 
SET @dt = '2010-01-01'
declare @dtEnd datetime 
SET @dtEnd = '2010-12-04'
DECLARE @day AS NVARCHAR(30)

WHILE (@dt < @dtEnd) BEGIN
--    insert into table(datefield)
--        values(@dt)
    SET @day =  UPPER(DATENAME(weekday,@dt))
    IF @day = 'MONDAY'
    --PRINT 'date is: ' + CAST(@dt AS VARCHAR(30))
    BEGIN
        PRINT 'date is: ' + CAST(@dt AS VARCHAR(30))  + ' ' + @day
    END
    SET @dt = DATEADD(day, 1, @dt)
END
Was it helpful?

Solution

The code you show seems to work, but it can be made more efficient. The code I show below will calculate the first Monday on or after the start date. Then it is used in the same loop but we simply add 7 days each time through the loop.

declare @dt datetime,
        @dtEnd datetime 

SET @dt = '2010-01-01'
SET @dtEnd = '2010-12-04'

Set @dt = DateAdd(Day, 7 - DateDiff(Day, 0, @dt) % 7, @dt)

WHILE (@dt < @dtEnd) BEGIN
    PRINT 'date is: ' + CAST(@dt AS VARCHAR(30))  + ' ' + DateName(Weekday, @dt)
    SET @dt = DATEADD(day, 7, @dt)
END

One thing I notice about your code is that you are using DateName, which works ok for displaying the weekday name, but not so good for making decisions (like you are doing). The problem with DateName is that it uses the language setting of the currently logged in user.

The following code shows this behavior.

set language 'spanish'
Select DateName(Weekday, GetDate())

set language 'us_english'
Select DateName(Weekday, GetDate())

Basically, if the language of a user was set to spanish, your code would fail but mine would not. Mine works because it uses the fact that January 1, 1900 was a Monday. It calculates the number of days and takes a mod of that and uses that mod to add the correct number of days. Since January 1, 1900 will always be a Monday, and we are not using the DateName function, this code will work without regard to the language setting.

OTHER TIPS

SELECT * from table t
WHERE t.date between 'startDate' and 'endDate'
AND (SELECT DATEPART(dw,t.StudyDate))=2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top