I'm using SQL Server 2005, trying to build a stored procedure or even a DTS (or SSIS now...) package that will execute properly for "Last Week" no matter when the procedure is run.
I am trying to figure out how to configure the starting and ending datetime values to always set to the beginning of the previous week (assuming Sunday is the setting in DATEFIRST) and the end of the previous week.
For example, no matter what day or time the query is executed by a user, I need the first (starting) datetime value to set to Sunday's date, at 12:00:00.003, and the second (ending) value to be set to Saturday's date at 11:59:59.997--FOR THE PREVIOUS WEEK.
I thought I was pretty good at using datepart, and I tried using that, with limited results. I've been able to get part of the way there with the following:
However, that is a "moving" or hard coded value (7 and 1), which is not going to work. Also, the getdate() function works great, and includes the time when the query is run, so anything that was done before the current time 7 days ago is omitted.
I'm sure this can be done using a CASE statement (or 2) and CONVERT or CAST. I've used a lot of CASE statements, but have never used (very well) CONVERT or CAST.
Any ideas?
I am trying to figure out how to configure the starting and ending datetime values to always set to the beginning of the previous week (assuming Sunday is the setting in DATEFIRST) and the end of the previous week.
For example, no matter what day or time the query is executed by a user, I need the first (starting) datetime value to set to Sunday's date, at 12:00:00.003, and the second (ending) value to be set to Saturday's date at 11:59:59.997--FOR THE PREVIOUS WEEK.
I thought I was pretty good at using datepart, and I tried using that, with limited results. I've been able to get part of the way there with the following:
Code:
SELECT * FROM SomeTable
WHERE DateAndTime BETWEEN getdate() - 7 AND getdate() -1
I'm sure this can be done using a CASE statement (or 2) and CONVERT or CAST. I've used a lot of CASE statements, but have never used (very well) CONVERT or CAST.
Any ideas?