我对此程序有疑问。它使用了几个临时表,它们会丢弃并重新创建。这导致了大量的崩溃,我只能假设冲突正在发生。
ALTER PROCEDURE [dbo].[AdditionalVisits_SelectByOrigID]
(
@orig_job_ID int
)
as
if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'additionalVisitsPodsCnt')
drop table additionalVisitsPodsCnt;
SELECT CONVERT(bit, COUNT(PODS.podID)) AS cnt, AdditionalVisits.this_job_id, AdditionalVisits.orig_job_id
INTO additionalVisitsPodsCnt
FROM PODS RIGHT OUTER JOIN
AdditionalVisits ON PODS.jobID = AdditionalVisits.this_job_id
GROUP BY AdditionalVisits.this_job_id, AdditionalVisits.orig_job_id
HAVING (AdditionalVisits.orig_job_id = @orig_job_ID)
if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'additionalVisitsPhotosCnt')
drop table additionalVisitsPhotosCnt;
SELECT CONVERT(bit, COUNT(Photos.photoID)) AS cnt, AdditionalVisits.this_job_id, AdditionalVisits.orig_job_id
INTO additionalVisitsPhotosCnt
FROM Photos RIGHT OUTER JOIN
AdditionalVisits ON Photos.jobID = AdditionalVisits.this_job_id
GROUP BY AdditionalVisits.this_job_id, AdditionalVisits.orig_job_id
HAVING (AdditionalVisits.orig_job_id = @orig_job_ID)
SELECT AdditionalVisits.id, AdditionalVisits.this_job_ID, AdditionalVisits.orig_job_ID, AdditionalVisits.reason, AdditionalVisits.date, ThisJob.Job_Reference_No,
ThisJob.Job_POD_Filename, ThisJob.Job_Photo_Filename, ThisJob.Job_Signed_For_Name, ThisJob.Job_Value, ThisJob.Job_Advance_Payment,
ThisJob.Job_Eoj_Payment, ThisJob.Job_Status, ThisJob.Job_Date_Added, ThisJob.Job_Start_Date, additionalVisitsPhotosCnt.cnt AS Job_Photo_Supplied,
additionalVisitsPodsCnt.cnt AS Job_POD_Supplied
FROM AdditionalVisits INNER JOIN
Jobs AS ThisJob ON AdditionalVisits.this_job_ID = ThisJob.Job_ID INNER JOIN
additionalVisitsPodsCnt ON AdditionalVisits.this_job_ID = additionalVisitsPodsCnt.this_job_id INNER JOIN
additionalVisitsPhotosCnt ON AdditionalVisits.this_job_ID = additionalVisitsPhotosCnt.this_job_id
WHERE (AdditionalVisits.orig_job_ID = @orig_job_ID) AND (ThisJob.Job_Status <> 7)
我得到的错误如下:
Cannot drop the table 'additionalVisitsPodsCnt', because it does not exist or you do not have permission. There is already an object named 'additionalVisitsPodsCnt' in the database.
或
Invalid object name 'additionalVisitsPhotosCnt'.
这些错误是间歇性的。有时它只是有效。
有更好的方法吗?
答案 0 :(得分:0)
当然,如果此表仅用于此一个过程,请使用“真实”local temporary table(在tempdb
中创建),在表名前添加#
:
SELECT CONVERT(bit, COUNT(PODS.podID)) AS cnt,
AdditionalVisits.this_job_id, AdditionalVisits.orig_job_id
INTO #additionalVisitsPodsCnt
FROM PODS ....
这样,它就会与所有其他会话隔离,即使其他人对此过程进行了并发调用。
答案 1 :(得分:0)
这是我用于#temp表的正常模式。 (注意&#34;#&#34;前缀)。
IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
drop table #TableOne
end
CREATE TABLE #TableOne
(
SurrogateKey int ,
NameOf varchar(12)
)
/*
Do something with temp table
*/
IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
drop table #TableOne
end
答案 2 :(得分:0)
考虑使用表变量。
This StackOverflow topic解释它比我更好......;)