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

 

 

一月份的上班天数为

 

posted @ 2022-01-09 16:02  闪耀星空  阅读(1174)  评论(0编辑  收藏  举报