[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

microsoft.public.sqlserver.programming

calc start-of-week and end-of-week

John Grandy

3/27/2007 10:49:00 PM

I need to calculate a datetime for the start of the current week (Sunday
12:00:00AM) and a datetime for the end of the current week (Saturday
11:59:59 PM).

I've written some long-winded code to do this involving building up strings
and then explicitly or implicitly casting them to datetime.

But is there a better way ?


2 Answers

Uri Dimant

3/28/2007 6:13:00 AM

0

John
This UDF written by Steve Kass, it will give you some ideas

create function dbo.NthWeekDay(
@first datetime, ---'20070301
@nth tinyint, -- Which of them - 1st, 2nd, etc.
@dow tinyint -- Day of week we want
) returns datetime as begin
-- Note: Returns a date in a later month if @nth is too large

declare @result datetime
set @result = @first + 7*(@nth-1)
return @result + (7 + @dow - datepart(weekday,@result))%7
end

select dbo.NthWeekDay ('20070318',1,1),dbo.NthWeekDay ('20070318',1,7)









"John Grandy" <johnagrandy-at-gmail-dot-com> wrote in message
news:ubDntIMcHHA.984@TK2MSFTNGP04.phx.gbl...
>I need to calculate a datetime for the start of the current week (Sunday
>12:00:00AM) and a datetime for the end of the current week (Saturday
>11:59:59 PM).
>
> I've written some long-winded code to do this involving building up
> strings and then explicitly or implicitly casting them to datetime.
>
> But is there a better way ?
>


Hugo Kornelis

3/28/2007 10:49:00 PM

0

On Tue, 27 Mar 2007 15:49:27 -0700, John Grandy wrote:

>I need to calculate a datetime for the start of the current week (Sunday
>12:00:00AM) and a datetime for the end of the current week (Saturday
>11:59:59 PM).
>
>I've written some long-winded code to do this involving building up strings
>and then explicitly or implicitly casting them to datetime.
>
>But is there a better way ?

Hi John,

SELECT DATEADD(day,
DATEDIFF(day, '20070107', CURRENT_TIMESTAMP) / 7 * 7,
'20070107');

--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hug...