SELECT* FROM( SELECT ResourceBooking.*, CustomerInformation.CustomerName as CustomerName, CustomerInformation.Gender+'/'+ltrim(str(datediff(year,isnull(CustomerInformation.DateOfBirth,0),getDate()))) as AgeAndBirth, ResourceBookingType.BookingName AS BookingName, ResourceBookingType.BookingDescription AS BookingDescription, RES.ResourceTypeID as ResourceTypeID, RES.ResourceSubTypeID as ResourceSubTypeID, RES.ResourceGroupID as ResourceGroupID, RES.ResourceTableID as ResourceTableID, RES.ResourcePKField as ResourcePKField, RES.IDDescription as IDDescription, RES.DicriptionName as EmployeeUserName FROM ResourceBooking LEFTJOIN CustomerInformation ONltrim(rtrim(ResourceBooking.PatientID)) =ltrim(rtrim(CustomerInformation.CustomerID)) LEFTJOIN ResourceBookingType ON ResourceBooking.BookingTypeID=ResourceBookingType.BookingTypeID LEFTJOIN (SELECT Resource.*, IDDescription =CASE ResourceTables.ResourceTableName WHEN'PayrollEmployees'THEN (SELECT EmployeeID From PayrollEmployees where EmployeeID = Resource.ResourcePKField ) WHEN'Facility'THEN (SELECT FacilityID FROM Facility WHERE FacilityID =Resource.ResourcePKField) END, DicriptionName =CASE ResourceTables.ResourceTableName WHEN'PayrollEmployees'then (SELECT EmployeeUserName From PayrollEmployees where EmployeeID = Resource.ResourcePKField ) WHEN'Facility'THEN (SELECT FacilityDescription FROM Facility WHERE FacilityID =Resource.ResourcePKField) END FROM Resource leftjoin ResourceTables ON Resource.ResourceTableID = ResourceTables.ResourceTableID) AS RES ON ResourceBooking.ResourceID = RES.ResourceID ) AS ResourceBooking WHERE (ResourceBooking.CompanyID =@CompanyID) AND (ResourceBooking.DivisionID =@DivisionID) AND (ResourceBooking.DepartmentID =@DepartmentID) AND (ResourceBooking.ResourceBookingState <>'3') AND (((@ResourceGroupID<>''or@ResourceGroupIDisnotnull) and ResourceBooking.ResourceGroupID=@ResourceGroupID) or (@ResourceGroupID=''or@ResourceGroupIDisnull )) AND (((@EmployeeID<>''or@EmployeeIDisnotnull) and ResourceBooking.IDDescription=@EmployeeID) or (@EmployeeID=''or@EmployeeIDisnull)) AND (cast(convert(nvarchar(30),ResourceBooking.FromDateTime,10)asDateTime)=cast(@FromDateTimeasDateTime))