2012-04-12 67 views
0

我想從給定日期獲得的一週,爲了這個,我用DATENAME函數試圖讓週一樣,在SQL DATENAME函數

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

正在逐漸爲10.我想要得到的輸出本週的開始日期和結束日期,2012-03-04 to 2012-03-10可能嗎?

+1

您正在使用哪個數據庫服務器? – Vikram 2012-04-12 13:30:49

+0

sql 2008 ....... – shanish 2012-04-12 13:32:52

+0

是否可以在「2012-03-04至2012-03-10」 – shanish 2012-04-12 13:51:21

回答

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)); 
+0

這一列中顯示開始和結束日期,謝謝你的工作..... – shanish 2012-04-12 13:41:52

+0

是否可以在「2012-03-04至2012-03-10」 – shanish 2012-04-12 13:43:40

+1

@Shanish單列中顯示開始和結束日期是的,請參閱我的編輯。雖然請記住,組合結果實際上是文本,所以您將無法在不解析的情況下操作日期。 – Yuck 2012-04-12 13:52:03

1

嘗試以下方法,改變GETDATE你的日期

Select 
DateAdd(d, 1- DatePart(dw,GetDate()),GetDate()) FirstDayOfWeek, 
DateAdd(d, 7- DatePart(dw,GetDate()),GetDate()) LastDayOfWeek 
+0

感謝vickram,它的工作完美 – shanish 2012-04-12 13:42:07

+0

我知道了Vickram,感謝你的迴應 – shanish 2012-04-12 14:06:26

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