0

我想从给定日期获取星期,为此我尝试使用 DATENAME 函数来获取 WEEK,

 Select DateName(WEEK,'2012-03-09')

我得到的输出为 10。我想得到本周的开始日期和结束日期,这2012-03-04 to 2012-03-10可能吗?

4

3 回答 3

1

做这样的事情:

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));
于 2012-04-12T13:34:23.227 回答
1

尝试以下操作,将 getdate 更改为您的日期

Select 
DateAdd(d, 1- DatePart(dw,GetDate()),GetDate()) FirstDayOfWeek,
DateAdd(d, 7- DatePart(dw,GetDate()),GetDate()) LastDayOfWeek
于 2012-04-12T13:35:41.727 回答
0

这不依赖于 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
于 2012-04-13T12:53:36.107 回答