Reputation: 1984
I wanted to get the week from the given date, for this I tried with the DATENAME function to get the WEEK like,
Select DateName(WEEK,'2012-03-09')
am getting the output as 10. I want to get the starting date and ending date of this week like, 2012-03-04 to 2012-03-10
Is it possible?
Upvotes: 0
Views: 949
Reputation: 44326
This does not rely on your default setting of datefirst.
set datefirst 4 -- this row does nothing in this query.
-- It will hurt the queries using datepart though
declare @t table(dt datetime)
insert @t values('2012-03-09 11:12'), ('2012-03-10 11:12'),('2012-03-11 11:12')
-- week from sunday to saturday
Select dateadd(week, datediff(week, 0, dt),-1),
dateadd(week, datediff(week, 0, dt),+5)
from @t
Upvotes: 0
Reputation: 50855
Do something like this:
DECLARE @MyDate Date = '2012-03-09';
-- This gets you the SUNDAY of the week your date falls in...
SELECT DATEADD(DAY, -(DATEPART(WEEKDAY, @MyDate) - 1), @MyDate);
-- This gets you the SATURDAY of the week your date falls in...
SELECT DATEADD(DAY, (7 - DATEPART(WEEKDAY, @MyDate)), @MyDate);
-- This will show the range as a single column
SELECT
CONVERT(NVarChar, DATEADD(DAY, -(DATEPART(WEEKDAY, @MyDate) - 1), @MyDate))
+ ' through ' +
CONVERT(NVarChar, DATEADD(DAY, (7 - DATEPART(WEEKDAY, @MyDate)), @MyDate));
Upvotes: 1
Reputation: 8333
try the following, change getdate to your date
Select
DateAdd(d, 1- DatePart(dw,GetDate()),GetDate()) FirstDayOfWeek,
DateAdd(d, 7- DatePart(dw,GetDate()),GetDate()) LastDayOfWeek
Upvotes: 1