SQL Server 2008
这是我上一个问题的延续。现在我尝试创建存储过程,但是我无法执行它。执行时,会显示错误消息 "无法删除表#MyReport",因为它不存在或您没有权限。
请指导我正确的方向。
以下是我存储的程序
Create PROCEDURE [dbo].[SEL_MyReport]
(
@employeeid int,
@date1 datetime,
@date2 datetime
)
AS
BEGIN
drop table #MyReport
Create Table #MyReport
(
employeeid int,
name varchar(30),
department varchar(30),
checkTime datetime
)
if (@employeeid > 0)
Begin
INSERT INTO #MyReport (employeeid,name, department, checkTime)
select emp.EmpolyeeID, emp.Name,dep.DeptName,tm.checkTime
from TimeInOut tm
left join Employee emp on emp.EmpolyeeId = tm.EmployeeId
left join Department dep on dep.DeptID = emp.defaultDeptID
where (DATEDIFF(s,@date1,tm.checktime) >=0
and DATEDIFF(s,@date2,tm.checktime)<=0) and emp.employeeID = @employeeid
SELECT
employeeid
,name
,department
,[Time In] = MIN(checkTime)
,[Time Out] = MAX(checkTime)
FROM #MyReport
GROUP BY employeeid,name, department, CAST(checktime AS DATE)
End
Else
Begin
INSERT INTO #MyReport (employeeid,name, department, checkTime)
select emp.EmpolyeeID, emp.Name,dep.DeptName,tm.checkTime
from TimeInOut tm
left join Employee emp on emp.EmpolyeeId = tm.EmployeeId
left join Department dep on dep.DeptID = emp.defaultDeptID
where (DATEDIFF(s,@date1,tm.checktime) >=0
and DATEDIFF(s,@date2,tm.checktime)<=0)
SELECT
employeeid
,name
,department
,[Time In] = MIN(checkTime)
,[Time Out] = MAX(checkTime)
FROM #MyReport
GROUP BY employeeid,name, department, CAST(checktime AS DATE)
End
END
Go
exec SEL_MyReport('639','05/01/2014','05/08/2014')
答案 0 :(得分:0)
好吧,由于存储过程的第一步尝试删除表,如果该表不存在,这显然会导致错误。
要解决此问题,请确保在删除表之前检查表是否存在:
IF OBJECT_ID('tempdb..#MyReport') IS NOT NULL DROP
TABLE #MyReport
答案 1 :(得分:0)
我会改变一下 - 这是代码。
你会注意到
@employeeid
> 0)已被更详细的WHERE
条款取代#tables
不需要SELECT
就足够了不幸的是,我没有任何可以测试的东西,但你应该理解它的一般印象。 此外,你的日期过滤似乎很奇怪,所以我认为你可能有其他意思 - 我可能会弄错。无论哪种方式,现在完成日期过滤的方式是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