SQL Server:当前命令发生严重错误。结果(如果有的话)应该被丢弃

时间:2012-11-11 11:23:46

标签: sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2

我在存储过程中有以下SQL Server查询,我从Windows应用程序运行此服务。我正在使用3000万条记录填充临时表变量,然后将它们与tbl_ref_test_main中的前几天记录进行比较,以添加和删除不同的记录。插入和删除时tbl_ref_test_main上有一个触发器。触发器在另一个表中写入相同的记录。由于对3000万条记录进行了比较,因此需要花费很长时间才能产生结果并抛出错误并说出A severe error occurred on the current command. The results, if any, should be discarded.

请提出任何建议。

提前致谢。

-- Declare table variable to store the records from CRM database
DECLARE @recordsToUpload TABLE(ClassId NVARCHAR(100), Test_OrdID NVARCHAR(100),Test_RefId NVARCHAR(100),RefCode NVARCHAR(100));

-- Populate the temp table
INSERT INTO @recordsToUpload
SELECT 
class.classid AS ClassId,
class.Test_OrdID AS Test_OrdID ,    
CAST(ref.test_RefId AS VARCHAR(100)) AS Test_RefId, 
ref.ecr_RefCode AS RefCode                  
FROM  Dev_MSCRM.dbo.Class AS class 
LEFT JOIN Dev_MSCRM.dbo.test_ref_class refClass ON refClass.classid = class.classid
LEFT JOIN Dev_MSCRM.dbo.test_ref ref ON refClass.test_RefId = ref.test_RefId
WHERE class.StateCode = 0
AND (ref.ecr_RefCode IS NULL OR (ref.statecode = 0 AND LEN(ref.ecr_RefCode )<= 18 ))                      
AND LEN(class.Test_OrdID )= 12
AND ((ref.ecr_RefCode IS NULL AND ref.test_RefId IS NULL) 
OR (ref.ecr_RefCode IS NOT NULL AND ref.test_RefId IS NOT NULL));                       

-- Insert new records to Main table
INSERT INTO dbo.tbl_ref_test_main
Select * from @recordsToUpload 
EXCEPT 
SELECT * FROM dbo.tbl_ref_test_main;

-- Delete records from main table where similar records does not exist in temp table
DELETE P FROM dbo.tbl_ref_test_main AS P
WHERE EXISTS
(SELECT P.* 
EXCEPT
SELECT * FROM @recordsToUpload);

-- Select and return the records to upload
SELECT Test_OrdID,
CASE 
WHEN RefCode IS NULL THEN 'NA' 
ELSE RefCode 
END,
Operation AS 'Operation' 
FROM tbl_daily_upload_records 
ORDER BY Test_OrdID, Operation, RefCode;

1 个答案:

答案 0 :(得分:0)

我的建议是3000万行对于表变量来说太大了,尝试创建一个临时表,用数据填充它然后在那里执行分析。 如果这不可能/合适,那么可能会创建一个永久表并在使用之间截断它。