tsql - SQL Server - Finding the first day of the week -


i've been looking around chunk of code find first day of current week, , everywhere see this:

dateadd(wk, datediff(wk,0,getdate()),0) 

every place says code i'm looking for.

the problem piece of code if run sunday chooses following monday.


if run:

select getdate() , dateadd(wk, datediff(wk,0,getdate()),0) 

results today (tuesday):

2013-05-14 09:36:39.650................2013-05-13 00:00:00.000 

this correct, chooses monday 13th.


if run:

select getdate()-1 , dateadd(wk, datediff(wk,0,getdate()-1),0) 

results yesterday (monday):

2013-05-13 09:38:57.950................2013-05-13 00:00:00.000 

this correct, chooses monday 13th.


if run:

select getdate()-2 , dateadd(wk, datediff(wk,0,getdate()-2),0) 

results 12th (sunday):

2013-05-12 09:40:14.817................2013-05-13 00:00:00.000 

this not correct, chooses monday 13th when should choose previous monday, 6th.

can illuminate me what's going in here? find hard believe no 1 has pointed out doesn't work, i'm wondering i'm missing.

try 1 -

set datefirst 1  declare @date datetime select @date = getdate()  select cast(dateadd(day, 1 - datepart(weekday, @date), @date) date)  select cast(@date - 2 date), cast(dateadd(wk, datediff(wk, 0, @date-2), 0) date) 

results:

---------- ---------- 2013-05-12 2013-05-13 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -