SQL Server - 把星期一(周一)当作每个星期的开始在一年中求取周数

-- The default first date in a week is Sunday, the value is 7
SELECT @@DATEFIRST  

-- Default DATEFIRST is Sunday
SELECT DATENAME(WEEK,'2013-12-31') AS WeekName  -- 53
SELECT DATENAME(WEEK,'2014-01-01') AS WeekName  -- 1
SELECT DATENAME(WEEK,'2014-01-05') AS WeekName  -- 2

-- Change the DATEFIRST to 1, Monday will be the first day of week.
SET DATEFIRST 1 

SELECT @@DATEFIRST  -- 1

-- After change the DATEFIRST to Monday
SELECT DATENAME(WEEK,'2013-12-31') AS WeekName  -- 53
SELECT DATENAME(WEEK,'2014-01-01') AS WeekName  -- 1
SELECT DATENAME(WEEK,'2014-01-05') AS WeekName  -- 1

要注意的是 SET DATEFIRST 只在当前执行中有效,也就说比如新开一个查询页面继续查询 SELECT @@DATEFIRST 则还是显示默认值 7。


其余时间计算:

SELECT CONVERT(varchar(10), getdate(), 120)--当前年月日,Example:2013-11-19
SELECT CONVERT(varchar(10), getdate(), 112)--当前年月日,Example:20131119
SELECT CONVERT(varchar(10), getdate(), 108)--当前年月日,Example:20:28:36
SELECT DATENAME (day ,getdate())--当月几号
SELECT DATENAME (month ,getdate())--月份
SELECT DATENAME (quarter ,getdate())--季度
SELECT DATENAME (dayofyear ,getdate())--一年中的第几天
SELECT DATENAME(week,GETDATE())--一年中第几周
SELECT DATENAME(weekday,GETDATE())--星期几
SELECT DATENAME(hour,GETDATE())--当前几点,24小时制的
SELECT DATENAME(minute,GETDATE())--取当前分钟数
SELECT DATENAME(second,GETDATE())--取当前秒数
SELECT DATENAME(millisecond,GETDATE())--毫秒


你可能感兴趣的:(SQL Server - 把星期一(周一)当作每个星期的开始在一年中求取周数)