There is quite a bit I would change - here is the code.
You will notice
- branching logic (if
@employeeid
> 0) has been replaced by a slightly more verboseWHERE
clause - no need for
#tables
as far as I can tell, theSELECT
should suffice
Unfortunately, I do not have anything to test against, but you should understand the general impression of it. Further, your date filtering seemed quite strange, so I assumed you may have meant something else - I could be mistaken. Either way, the way the date filtering is now done is SARGable
CREATE PROCEDURE [dbo].[SEL_MyReport]
(
@employeeid INT,
@date1 DATETIME,
@date2 DATETIME
)
AS
BEGIN
SET NOCOUNT ON;
SELECT emp.EmpolyeeID
,emp.Name
,dep.DeptName
,[Time In] = MIN(tm.checkTime)
,[Time Out] = MAX(tm.checkTime)
FROM TimeInOut tm
LEFT
JOIN Employee emp on emp.EmpolyeeId = tm.EmployeeId
LEFT
JOIN Department dep on dep.DeptID = emp.defaultDeptID
WHERE tm.checktime >= @date1
AND tm.checktime <= @date2
/***********************************************************************************************************
* I've assumed what you may be trying to express, above
* You might also want to look at the BETWEEN() operator, remembering that it is inclusive in its behaviour
* (DATEDIFF(s,@date1,tm.checktime) >=0
* AND DATEDIFF(s,@date2,tm.checktime)<=0)
***********************************************************************************************************/
AND (emp.employeeID = @employeeid OR @employeeid <= 0)
GROUP BY emp.EmpolyeeID, emp.name, dep.department, CAST(tm.checktime AS DATE)
END
GO