Skip to content
Advertisement

Calculate amount of days worked by employee from 1 column to another with a function

This is my function I have so long, I need to be able to just call it with with an Employee number from the Employee table and it has to calculate the days between the 2 columns.

CREATE FUNCTION getDaysWorked (@Employee_No int)
Returns Datetime  
as  
Begin   
declare @DayStart datetime  
declare @DayResigned datetime
declare @DaysWorked int
  
set @DayStart =   (Select e.Group_Start_Date) from Employee e
set @DayResigned =(Select e.ResignDate) from Employee e
set @DaysWorked = (@DayStart - @DayResigned) 
Return(@DaysWorked)  
end  
GO

If there is a better way please let me know, this is what I have…

Advertisement

Answer

Presumably, you want something related to the employee being passed in. I would surmise:

create function getDaysWorked (@Employee_No int)
returns int as  
begin   
    declare @DaysWorked int;
  
    select @DaysWorked = datediff(day, e.Group_Start_Date, e.ResignDate)
    from Employee e
    where e.Employee_No = @Employee_No;

    return(@DaysWorked)  
end;

Note that the function returns an integer not a date.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement