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.