关于sql数据库里日期的跨年处理:
读取本周和上周纪录时,涉及跨年数据要特殊处理:
数据库里周数保存 1-52周。
按照sql函数取得周数时会出现53的问题。
写入数据库时要处理州周为53的情况,
week=53 则当作下1年处理
nian=nian+1
week=1
本周:
SET DATEFIRST 1 -- 设置周一为一周的第一天
declare @week_year int
set @week_year = year(getdate())
declare @week smallint -- 第几周
select @week = datepart(week,getdate())
if(@week=53)
begin
set @week_year=@week_year+1
set @week=1
end
上周:
SET DATEFIRST 1 -- 设置周一为一周的第一天
declare @last_week_year int
set @last_week_year = year(getdate())
declare @last_week smallint -- 第几周
select @last_week = datepart(week,getdate())
if(@last_week=1)
begin
set @last_week_year=@last_week_year-1
set @last_week=52
end
else
begin
set @last_week=@last_week-1
end
上上周:
SET DATEFIRST 1 -- 设置周一为一周的第一天
declare @last_last_week_year int
set @last_last_week_year = year(getdate())
declare @last_last_week smallint -- 第几周
select @last_last_week = datepart(week,getdate())
if(@last_last_week=1)
begin
set @last_last_week_year=@last_last_week_year-1
set @last_last_week=51
end
else if(@last_last_week=2)
begin
set @last_last_week_year=@last_last_week_year-1
set @last_last_week=52
end
else
begin
set @last_last_week=@last_last_week-2
end
本月:
declare @today_year int
declare @today_month int
set @today_year = year(getdate())
set @today_month = month(getdate())
上月:
declare @last_month_year int
declare @last_month int
set @last_month_year = year(getdate())
set @last_month = month(getdate())
if (@last_month = 1)
begin
set @last_month = 12
set @last_month_year =@last_month_year -1
end
else if (@last_month != 1)
begin
set @last_month = @last_month-1
end