我有一个存储过程,它将记录从详细信息表复制到历史记录表。它将在一天内运行一次。详细表中的记录量是几十万。将详细信息复制到历史记录表需要2个多小时。
如何改善表现?
我的程序:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[sp_Job_Archive_Record_Count]
@p_ToDate DATETIME,
@p_Detail_Ins INT OUTPUT,
@p_Detail_Del INT OUTPUT,
@p_Header_Ins INT OUTPUT,
@p_Header_Del INT OUTPUT
as
BEGIN TRAN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
INSERT into tbl_Detail_History
SELECT * FROM tbl_Detail WITH(NOLOCK)
WHERE i_HeaderKey IN
(SELECT i_HeaderKey FROM tbl_Header WITH(NOLOCK)
WHERE d_dateTime <= cast(@p_ToDate AS DATETIME)
)
SET @p_Detail_Ins = @@ROWCOUNT
INSERT INTO tbl_Archive_Count values('Detail',@p_Detail_Ins,getdate (),@p_ToDate)
DELETE FROM tbl_detail
WHERE i_DetailKey IN
(SELECT i_DetailKey FROM tbl_Detail_History WITH(NOLOCK))
SET @p_Detail_Del = @@ROWCOUNT
INSERT INTO tbl_Header_History
SELECT * FROM tbl_Header WITH(NOLOCK)
WHERE d_dateTime <= cast(@p_ToDate as DATETIME)
SET @p_Header_Ins = @@ROWCOUNT
INSERT INTO tbl_Archive_Count values('Header',@p_Header_Ins,getdate(),@p_ToDate)
DELETE FROM tbl_Header
WHERE i_Headerkey IN
(SELECT i_HeaderKey FROM tbl_Header_History WITH(NOLOCK))
SET @p_Header_Del = @@ROWCOUNT
IF (@@ERROR <> 0)
BEGIN
ROLLBACK TRAN
END
COMMIT TRAN
答案 0 :(得分:-1)
取决于tbl_detail和tbl_detail_history之间的索引和行比率的变化
DELETE FROM tbl_detail
WHERE i_DetailKey IN
(SELECT i_DetailKey FROM tbl_Detail_History WITH(NOLOCK))
到
DELETE FROM tbl_detail D
WHERE exists (select 1 from FROM tbl_Detail_History WITH(NOLOCK) where i_DetailKey = d.i_DetailKey)
可以使用tbl_header删除进行类似的更改。如果你获得性能提升,你会寻找我还建议删除无锁提示,特别是删除语句,因为你可能会导致自己在那里有完整性问题。看看可以有益的read_committed_snapshot
HTH