使用函数内的两个日期从另一个表中排除天数

时间:2014-06-08 06:00:20

标签: sql sql-server-2012

我创建了一个存储过程来计算员工的休假日,我需要删除另一个表中存在的所有假期。

以下是我从度假时间中删除星期五的功能:

ALTER FUNCTION [VSRC].[CalculateNumberOFWorkDays] 
   (@StartDate datetime, @EndDate datetime)
RETURNS int
AS
BEGIN
   SET @StartDate = DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0) 
   SET @EndDate = DATEADD(dd, DATEDIFF(dd, 0, @EndDate), 0)

   DECLARE @WORKDAYS INT
   SELECT @WORKDAYS = (DATEDIFF(dd, @StartDate, @EndDate) + 1)
                      - (DATEDIFF(wk, @StartDate, @EndDate) * 1)
                      - (CASE WHEN DATENAME(dw, @StartDate) = 'Friday' THEN 1 ELSE 0 END)
                      - (CASE WHEN DATENAME(dw, @EndDate) = 'Friday' THEN 1 ELSE 0 END)
   RETURN @WORKDAYS
END

我将startdateenddate作为参数发送给该函数,它将返回没有星期五的休假天数,现在我需要排除此表中存在的所有日期:

CREATE TABLE [VSRC].[tbHolydays]
(
    [HolydayID] [int] IDENTITY(1,1) NOT NULL,
    [HolydayName] [nvarchar](150) NULL,
    [HolydayDate] [date] NULL,

    CONSTRAINT [PK_tbHolydays] PRIMARY KEY CLUSTERED ([HolydayID] ASC)
) ON [PRIMARY]

1 个答案:

答案 0 :(得分:1)

您可以将代码更改为:

SELECT @WORKDAYS =  (DATEDIFF(dd, @StartDate, @EndDate) + 1)
                    -(DATEDIFF(wk, @StartDate, @EndDate) * 1)
                    -(CASE WHEN DATENAME(dw, @StartDate) = 'Friday' THEN 1 ELSE 0 END)
                    -(CASE WHEN DATENAME(dw, @EndDate) = 'Friday' THEN 1 ELSE 0 END)
                    -(SELECT COUNT(*) FROM [VSRC].[tbHolydays] WHERE HolydayDate BETWEEN @StartDate AND @EndDate)