SQL server自動創建日歷表。


做日報功能需要統計每個月的上班天數,節假日因為每年的日期都不一樣,所以需要自己手動更新這些節假日

1:首先先自動創建一個日歷表,選擇開始年月日和結束的年月日

不要同時執行,先執行創建表之后
CREATE TABLE [dbo].[time_dimension] ( [time_id] [
int] IDENTITY (1, 1) NOT NULL , [the_date] [datetime] NULL , [the_day] [nvarchar] (15) NULL , [the_month] [nvarchar] (15) NULL , [the_year] [smallint] NULL , [day_of_month] [smallint] NULL , [holiday_type] [int] NULL ) ON [PRIMARY] 再執行存儲過程 DECLARE @WeekString varchar(12), @dDate SMALLDATETIME, @sMonth varchar(20), @iYear smallint, @iDayOfMonth smallint, @iWeekOfYear smallint, @iMonthOfYear smallint, @sQuarter varchar(2), @sSQL varchar(100), @adddays int SELECT @adddays = 1 --日期增量(可以自由設定) SELECT @dDate = '01/01/2021 ' --開始日期 WHILE @dDate < '12/31/2022 ' --結束日期 BEGIN SELECT @WeekString = DATENAME (dw, @dDate) SELECT @sMonth=DATENAME(mm,@dDate) SELECT @iYear= DATENAME (yy, @dDate) SELECT @iDayOfMonth=DATENAME (dd, @dDate) SELECT @iWeekOfYear= DATENAME (week, @dDate) SELECT @iMonthOfYear=DATEPART(month, @dDate) SELECT @sQuarter = 'Q ' + CAST(DATENAME (quarter, @dDate)as varchar(1)) INSERT INTO time_dimension(the_date, the_day, the_month, the_year, day_of_month ) VALUES (@dDate, @WeekString, @sMonth, @iYear, @iDayOfMonth) SELECT @dDate = @dDate + @adddays END GO

效果圖

 

 接下來就是修改工作日類型了,上網搜索日歷看每個假期的具體放假日子進行修改工作日類型了,這個過程就比較繁瑣了

 

 

--先把工作類型默認為工作日
update time_dimension set holiday_type=1

--根據條件把周六周日修改為2周末
update time_dimension set holiday_type=2 where the_day='星期六' or the_day='星期日'

--比如2022-01工作的天數
update time_dimension set holiday_type=3 where the_year=2022 and the_month=01 and day_of_month between 1 and 3
update time_dimension set holiday_type=3 where the_year=2022 and the_month=01 and day_of_month=31
--把2022-01周六周日調休改成工作日
update time_dimension set holiday_type=1 where the_year=2022 and the_month=01 and day_of_month between 29 and 30
--統計2022—01的工作總天數
select count(holiday_type) from time_dimension where holiday_type=1 and the_year=2022 and the_month=01

 

 

一月份的上班天數為

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM