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?
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));
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.