Sql server queries the number of working days, the number of rest days and other date operations in the specified time interval

1. Query the working days in the specified time interval

The main difficulty is the statutory holidays, which vary from year to year in the country, and also involve the adjustment of leave, so we design a holiday table. The main fields are year, type (whether or not to take leave), and holiday date. as follows:

CREATE TABLE [dbo].[Holidays](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Holiday] [datetime2](7) NULL,--假期日期
[YearS] [char](4) NULL,--年份
[daytype] [int] NULL--类型
)

 

Add the holidays and days off for the current year

Write a method to calculate the working days except statutory holidays

ALTER FUNCTION [dbo].[GetWorkerDays]
(
-- Add the parameters for the function here
 @StartTime DATETIME, -- 起始时间
 @EndTime DATETIME -- 结束时间,查询默认小于此时间
)
RETURNS INT
AS
BEGIN
DECLARE @Total INT;
DECLARE @Temp INT;
DECLARE @Days INT;
DECLARE @Index INT;
SET @Days = DATEDIFF(DAY,@StartTime,@EndTime);
SET @Index = 0;
SET @Temp = 0;
SET @Total = 0;
WHILE @Index < @Days BEGIN
SET @Temp = DatePart(WEEKDAY,DATEADD(DAY,@Index,@StartTime));
IF @Temp > 1 AND @Temp < 7 BEGIN
SET @Total = @Total + 1;
END
SET @Index = @Index + 1;
END
RETURN ISNULL(@Total,0)
END

 

After executing this table-valued function, adding the holiday and subtracting the legal holiday is the working day. You can write another stored procedure.

2. Calculate the rest days of the specified date range

This is the opposite of that, that is, Sunday plus statutory holidays minus days off

we write a function

ALTER FUNCTION GetRestDays
(
@StartTime DATETIME2,
@EndTime DATETIME2
)
RETURNS INT
AS
BEGIN
DECLARE @LegalRest INT --法定假期
DECLARE @AdjustmentDay INT--调休上班时间
DECLARE @SurplusDay INT --剩余工作日
DECLARE @CountDay INT --总共天数
SELECT @LegalRest=COUNT(0) FROM dbo.Holidays WHERE daytype=1 AND  YearS=YEAR(GETDATE()) AND MONTH(Holiday)=MONTH(GETDATE())
AND Holiday>=@StartTime AND Holiday<=@EndTime
SELECT  @AdjustmentDay=COUNT(0) FROM dbo.Holidays WHERE daytype=2 AND  YearS=YEAR(GETDATE()) AND MONTH(Holiday)=MONTH(GETDATE())
AND Holiday>=@StartTime AND Holiday<=@EndTime
 SET @SurplusDay= [dbo].[GetWorkerDays](@StartTime,DATEADD(DAY,1,@EndTime))--剩余工作日
 SELECT @CountDay=COUNT(0) FROM dbo.TimeSpanDays(@StartTime ,DATEADD(DAY,1,@EndTime))  --总共天数  计算出 时间段总共天数
 return @CountDay-@SurplusDay+@LegalRest-@AdjustmentDay
END

 

3. Calculate the date of the beginning of the month and the date of the end of the current month

the beginning of the month

Simple:

SELECT  CONVERT(VARCHAR(7),GETDATE(),120)+'-01'

month end date

This is also simple and simple: it is the first day of the month plus one month and then minus one day

SELECT   DATEADD(DAY,-1, DATEADD(MONTH,1, CONVERT(VARCHAR(7),GETDATE(),120)+'-01'))

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/130354298