USE [EnVisage] GO /****** Object: UserDefinedFunction [dbo].[resourceAvailability_f] Script Date: 01/26/2016 11:16:17 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[resourceAvailability_f](@StartDate datetime, @EndDate datetime) RETURNS @restable TABLE (FirstName varchar(100), LastName varchar(100), ExpenditureCategory varchar(100), AvailableHours float, AllocatedHours float, TrainingHours float, VacationHours float, ResourceAvailability float, TeamName varchar(100) ) AS BEGIN INSERT INTO @restable select vw.FirstName, vw.LastName, vw.Name as ExpenditureCategory, vw.AvailableHours, vw.AllocatedHours, vw.TrainingHours, vw.VacationHours, vw.AvailableHours-vw.AllocatedHours-vw.TrainingHours-vw.VacationHours as ResourceAvailability, vw.TeamName From( select pr.FirstName, pr.LastName, ec2.Name, (select t.Name from Team t where pr.TeamId=t.Id) as TeamName, ((select UOM.UOMValue from UOM, ExpenditureCategory ec where UOM.Id=ec.UOMId and ec.Id=pr.ExpenditureCategoryId)*(DATEDIFF(WEEK, (case when pr.StartDate > @StartDate then pr.StartDate else @StartDate end), (case when pr.EndDate < @EndDate then pr.EndDate else @EndDate end)))) as AvailableHours, ISNULL((select SUM (pa.Quantity) From PeopleResourceAllocation pa Where pa.PeopleResourceId=pr.Id and pa.WeekEndingDate between @StartDate and @EndDate), 0) as AllocatedHours, ISNULL((select SUM (pt.HoursOff) From PeopleResourceTraining pt Where pt.PeopleResourceId=pr.Id and pt.WeekEndingDate between @StartDate and @EndDate), 0) as TrainingHours, ISNULL((select SUM (pv.HoursOff) From PeopleResourceVacation pv Where pv.PeopleResourceId=pr.Id and pv.WeekEndingDate between @StartDate and @EndDate), 0) as VacationHours from PeopleResource pr, ExpenditureCategory ec2 where ec2.Id=pr.ExpenditureCategoryId) as vw RETURN END GO