Real Working Days SQL SERVER

         

CREATE PROCEDURE pro_GenerateWorkingDays
AS
BEGIN
delete from [dbo].[tab_RealWorkingDays]
declare @yearMonth varchar(50);

declare cur_date cursor
for
select YearMonth from [dbo].[view_RecentThreeYearsMonths]

open cur_date

fetch next from cur_date into @yearMonth
while @@FETCH_STATUS=0
begin
print @yearMonth

DECLARE @theDate datetime
declare @realWorkingDays int

SET @theDate = convert(datetime,replace(@yearMonth,'-','')+'01')
SELECT @realWorkingDays=20 + COUNT(*)
FROM (
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, @theDate), 28) AS theDate UNION
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, @theDate), 29) UNION
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, @theDate), 30)
) AS d
WHERE DATEPART(DAY, theDate) > 28
AND DATEDIFF(DAY, 0, theDate) % 7 < 5

print @realWorkingDays

---- cause of holiday so working day off -------------
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
declare @workdayOff int
set @workdayOff=0

declare cur_holiday cursor for
select startdate,enddate from [dbo].[tab_PublicHoliday] where convert(varchar,startdate) like '%'+@yearMonth+'%'

open cur_holiday
fetch next from cur_holiday into @StartDate,@EndDate
while @@FETCH_STATUS=0
begin
declare @workdayOff2 int
SELECT
@workdayOff2=
(DATEDIFF(dd, @StartDate, @EndDate) + 1)
-(DATEDIFF(wk, @StartDate, @EndDate) * 2)
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)

set @workdayOff=@workdayOff+@workdayOff2;
fetch next from cur_holiday into @StartDate,@EndDate
end
close cur_holiday
deallocate cur_holiday

print @workdayOff

----end cause of holiday so working day off -------------

-----weekend need work--------------------
declare @weekendWork int;
select @weekendWork=[WeekendWorkdays] from [dbo].[tab_WeekendWorkdays] where
convert(date,cast([YEAR] as varchar)+'-'+cast([month] as varchar)+'-'+'01') = CONVERT(date,@yearMonth+'-01')
print @weekendwork
-----end weekend need work--------------------

set @realWorkingDays=@realWorkingDays-@workdayOff+@weekendwork
print @realWorkingDays
insert into [dbo].[tab_RealWorkingDays]([YearMonth],[WorkingDay])
values(@yearMonth,@realWorkingDays)
fetch next from cur_date into @yearMonth
end
close cur_date
DEALLOCATE cur_date;
END
GO

猜你喜欢

转载自www.cnblogs.com/Javi/p/12096333.html