關於sql中日期相關跨年處理

來源:互聯網
上載者:User

 

關於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
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.