若是我有一個日期01/01/2009,我想知道它是什麼日子,例如週一,週二等... sql
SQL Server 2005/2008中是否有內置函數? 或者我須要使用輔助表嗎? 函數
SELECT DATENAME(dw,GETDATE()) -- Friday SELECT DATEPART(dw,GETDATE()) -- 6
儘管SQLMenace的答案已被接受,但您應該注意一個重要的SET
選項 code
SET DATEFIRST get
DATENAME將返回正確的日期名稱,但若是已更改星期的第一天,則返回相同的DATEPART值,以下圖所示。 string
declare @DefaultDateFirst int set @DefaultDateFirst = @@datefirst --; 7 First day of week is "Sunday" by default select [@DefaultDateFirst] = @DefaultDateFirst set datefirst @DefaultDateFirst select datename(dw,getdate()) -- Saturday select datepart(dw,getdate()) -- 7 --; Set the first day of week to * TUESDAY * --; (some people start their week on Tuesdays...) set datefirst 2 select datename(dw,getdate()) -- Saturday --; Returns 5 because Saturday is the 5th day since Tuesday. --; Tue 1, Wed 2, Th 3, Fri 4, Sat 5 select datepart(dw,getdate()) -- 5 <-- It's not 7! set datefirst @DefaultDateFirst
這是個人代碼的工做副本檢查它,如何在sql中從日期中檢索日期名稱 io
CREATE Procedure [dbo].[proc_GetProjectDeploymentTimeSheetData] @FromDate date, @ToDate date As Begin select p.ProjectName + ' ( ' + st.Time +' '+'-'+' '+et.Time +' )' as ProjectDeatils, datename(dw,pts.StartDate) as 'Day' from ProjectTimeSheet pts join Projects p on pts.ProjectID=p.ID join Timing st on pts.StartTimingId=st.Id join Timing et on pts.EndTimingId=et.Id where pts.StartDate >= @FromDate and pts.StartDate <= @ToDate END
您可能會發現此版本頗有用。 table
-- Test DATA select @@datefirst create table #test (datum datetime) insert #test values ('2013-01-01') insert #test values ('2013-01-02') insert #test values ('2013-01-03') insert #test values ('2013-01-04') insert #test values ('2013-01-05') insert #test values ('2013-01-06') insert #test values ('2013-01-07') insert #test values ('2013-01-08') -- Test DATA select Substring('Sun,Mon,Tue,Wed,Thu,Fri,Sat,Sun,Mon,Tue,Wed,Thu,Fri,Sat', (DATEPART(WEEKDAY,datum)+@@datefirst-1)*4+1,3),Datum from #test
歐洲: function
declare @d datetime; set @d=getdate(); set @dow=((datepart(dw,@d) + @@DATEFIRST-2) % 7+1);