I am attempting to create a function that incorporates multiple ‘With’ Statements.
My original Query is:
WITH EmpCount as
(
SELECT job.EmployeeID, assign.PropertyID FROM EmployeeJobstatus job
JOIN Assignment assign ON job.JobID = assign.ID GROUP by job.EmployeeID,
assign.PropertyID
),
NoDup as
(
SELECT EmployeeID, Count(employeeID) as NO from EmpCount
Group by EmployeeID HAVING count(Employeeid) > 1
)
SELECT prop.Name, job.EmployeeID, Emp.EmpID, Emp.Name
from EmployeeJobStatus job
JOIN Assignment assign ON assign.id = job.jobid
JOIN Property prop ON prop.ID = assign.PropertyID
JOIN Employee emp on emp.ID = job.EmployeeID
WHERE EmployeeID IN (SELECT EmployeeID from NoDup)
GROUP By prop.Name, EmployeeID, emp.EmpID,Emp.Name
Order BY EmployeeID
This returns:
Name EmployeeID EmpID Name
Property 1 23 1286333 LastNameRemoved1, Rachel A
Property 2 23 1286333 LastNameRemoved1, Rachel A
Property 2 76 1268329 LastNameRemoved2, Tamer A
Property 1 76 1268329 LastNameRemoved2, Tamer A
Property 3 135 1411933 LastNameRemoved3, Sarah E
Property 1 135 1411933 LastNameRemoved2, Sarah E
My function needs to return a ‘Y’ or a ‘N’ depending on whether or not they were cross property, utilizing the fields in EmployeeJobStatus StartDate and EndDate.
I have only started my function, as I have no idea what to do next.
CREATE function dbo.IsEmployeeCrossPropertyOnDate
(@EmpID int, @AsOfDate datetime)
RETURNS INT AS
Any help, or a nudge in the right direction would be much appreciated. Thank you.
How about this…
EDIT:
You’d probably outer apply it, rather than cross. Nulls would then be employees with no assignments at the point in time.
EDIT 2:
Since you asked, below is a scalar function. Just be careful of scalars. Depending on where you use it in a query, the BEGIN END block can fool the optimizer into going RBAR.