想知道今天是星期幾,可以用DATEPART,星期日回傳0、星期一回傳1,以此類推:
SELECT DATEPART(WEEKDAY, GETDATE())
若要產生一整年的日曆,並排除禮拜六日的做法,可利用DATEDIFF做到,
只要知道哪天是禮拜一,算出差異的天數並取7的餘數,再除掉上班日天數(5天),
從結果為1或0來判斷是否為周末,就能產生整年的行事曆:
DECLARE @sdate DATETIME, @edate DATETIME; SET @sdate = '20150101'; SET @edate = '20151231'; WITH cte AS ( SELECT workDate = @sdate UNION ALL SELECT workDate + 1 FROM cte WHERE (workDate < @edate) ) SELECT workDate FROM cte WHERE DATEDIFF(DAY, '19000101', workDate) % 7 / 5 = 0 OPTION (MAXRECURSION 0); --MAXRECURSION 0表示不設限,預設最大遞迴 100